Fluent Python Ch03
( 출처 : 전문가를 위한 파이썬 / Fluent Python )
[ Dictionaries and Sets ]
1. Mapping & Hashable
Dictionary는 “Mapping”이다!
from collections import abc
my_dict={}
isinstance(my_dict,abc.Mapping) # TRUE
All mapping types use the basic dict
in their implementation!
( + share limitation…. keys must be HASHABLE )
( HASHABLE하다 = 바뀔 수 없다! )
2. Dict Comprehension
>>> DIAL_CODES = [
... (86, 'China'),
... (91, 'India'),
... (1, 'United States'),
... (62, 'Indonesia'),
... (55, 'Brazil'),
... (92, 'Pakistan'),
... (880, 'Bangladesh'),
... (234, 'Nigeria'),
... (7, 'Russia'),
... (81, 'Japan'),
... ]
country_code = {country: code for code, country in DIAL_CODES}
3. update({key:val})
my_dict={}
my_dict.update({'lee':1})
my_dict.update({'park':2})
my_dict.update({'lee':3})
my_dict
# {'lee': 3, 'park': 2}
4. Handling Missing Keys with setdefault
dict[k]
& dict.get(k)
my_dict['lee']
my_dict['kim'] # 에러
#-----------------------------------------#
my_dict.get('lee')
my_dict.get('kim') # 아무 값도 반환 X
my_dict.get('kim',[]) # [] 반환
setdefault
my_dict={}
my_dict.update({'lee':1})
my_dict.update({'park':2})
#-----------------------------------------------#
my_dict.setdefault('kim',[]).append(3)
my_dict.setdefault('kim',[]).append(5)
my_dict
{'lee': 1, 'park': 2, 'kim': [3, 5]}
5. Defaultdict
collections.defaultdict
- create items on demand, whenever a missing key is searched!
Process : dd =defaultdict(list)
dd =defaultdict(list)
for i in range(10):
dd['key'].append(i)
dd
# defaultdict(list, {'key': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]})
6. Variations of dict
collections.OrderedDict
- maintains keys in insertion order
popitem
: FIRST itempopitem(last=True)
: LAST item
collections.Counter
ct = collections.Counter('abracadabra')
ct
# Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
ct.update('aaaaazzz')
ct
# Counter({'a': 10, 'z': 3, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
ct.most_common(2)
# [('a', 10), ('z', 3)]
7. Set
l = ['spam', 'spam', 'eggs', 'spam']
set(l)
# {'eggs', 'spam'}
list(set(l))
# ['eggs', 'spam']
union, intersection, difference
list1 = ['a', 'b', 'c', 'd','d','d','d']
list2 = ['c', 'd', 'e', 'f','f','f','f']
print(set(list1) - set(list2))
print(set(list1) & set(list2))
print(set(list1) | set(list2))
#-----------------------------------------#
{'b', 'a'}
{'d', 'c'}
{'f', 'd', 'c', 'e', 'a', 'b'}
8. 기타
(1) Key search is VERY FAST
(2) Key ordering depends on INSERTION order