1. A~Z의 딕셔너리 빨리 만들기
dic = dict(zip(string.ascii_lowercase,[0]*26))
2. 딕셔너리 키 기준 합치기
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
3. Find N'th Most Common Key-Vaue Pairs
Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
4. Different Ways to Create Dictionary
a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> f = dict({'one': 1, 'three': 3}, two=2)
>>> a == b == c == d == e == f
True
5. Python Fast Looping Two Lists to Create Dict
questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
'PYTHON LANGUAGE' 카테고리의 다른 글
2D Array (0) | 2022.06.25 |
---|---|
ZIP (aggregate two iterators as list of tuples) (0) | 2022.06.20 |
ITERTOOLS (0) | 2022.06.20 |
Sort (0) | 2022.06.19 |