1. dict.copy()
copy() 함수를 통해 새로운 객체를 복사하여 사용할 수 있다.
>>> dict1 = {'apple':1, 'banana':3, 'orange':5 }
>>> dict2 = dict1.copy() # 새로운 객체로 복사해서 할당 . dict1과 dict2는 서로 다른 객체
>>> dict2
{'apple': 1, 'banana': 3, 'orange': 5}
>>> dict1['apple'] =2
>>> dict1
{'apple': 2, 'banana': 3, 'orange': 5}
>>> dict2
{'apple': 1, 'banana': 3, 'orange': 5}
2. dict.fromkeys(iterable, value)
iterable을 key로 하고 value를 값으로하는 dictionary 생성. value는 optional이며 지정하지 않으면 None값이 설정
>>> keys = ['a','e','i','o','u']
>>> vowels = dict.fromkeys(keys
>>> print(vowels)
{'i': None, 'e': None, 'o': None, 'a': None, 'u': None}
>>> vowels = dict.fromkeys(keys,0)
>>> print(vowels)
{'i': 0, 'e': 0, 'o': 0, 'a': 0, 'u': 0}
3. dict.update()
dictionary를 update한다. 기존에 없는 key는 추가하고 기존에 존재하는 key일 경우 value를 엎어쓴다
>>> dict1 = {'apple':1, 'banana':3, 'orange':5 }
>>> dict2 = {'apple':1, 'orange':3 }
>>> dict1.update(dict2)
>>> dict1
{'apple': 1, 'banana': 3, 'orange': 3}
>>> dict2.update(dict1)
>>> dict2
{'apple': 1, 'orange': 3, 'banana': 3}
4. dictionary 병합하기 (value overwrite)
>>> dict1 = {'apple':1, 'banana':3, 'orange':5 }
>>> dict2 = {'apple':1, 'orange':3 }
>>> dict(dict1,**dict2)
{'apple': 1, 'banana': 3, 'orange': 3}
>>> dict(dict2,**dict1)
{'apple': 1, 'orange': 5, 'banana': 3}
5. dictionary 병합하기 (value add)
>>> dict1 = {'apple':1, 'banana':3, 'orange':5 }
>>> dict2 = {'apple':1, 'orange':3 }
>>> collections.Counter(dict1) + collections.Counter(dict2)
Counter({'orange': 8, 'banana': 3, 'apple': 2})
6. collections.defaultdict()
mylist = ['a','z','c','a','f','q','c']
위와 같은 리스트에서 각 값의 갯수를 구하는 딕셔너리는 아래와 같은 코드로 작성한다
>>> mylist = ['a','z','c','a','f','q','c']
>>> dict2 = {}
>>> for c in mylist:
if c in dict2:
dict2[c] += 1
else:
dict2[c] =1
collections의 defaultdict() 함수를 사용하면 아래와 같이 코드를 단축할 수 있다
>>> import collections
>>> dict1 = collections.defaultdict(int)
>>> for c in mylist:
dict[c] += 1
>>> dict1
defaultdict(<class 'int'>, {'a': 2, 'z': 1, 'c': 2, 'f': 1, 'q': 1})
'Tech-Pyhton' 카테고리의 다른 글
Numpy 요약 정리 (0) | 2020.04.04 |
---|---|
Numpy 설치하기 (1) | 2019.12.25 |
[Python] Map, Filter, Zip (0) | 2019.03.27 |
[Python] List Comprehension (0) | 2019.03.27 |
[Python] collections (0) | 2019.03.27 |
댓글