Created
October 4, 2015 16:03
-
-
Save poros/c22e83e936b9b4c9d809 to your computer and use it in GitHub Desktop.
Counting with dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
colors = ['green', 'blue', 'green', 'red', 'blue', 'green'] | |
d = {} | |
for color in colors: | |
if color not in d: | |
d[color] = 0 | |
d[color] += 1 | |
# slighlty better | |
d = {} | |
for color in colors: | |
d[color] = d.get(color, 0) + 1 | |
# way better | |
from collections import defaultdict | |
d = defauultdict(int) | |
for color in colors: | |
d[color] += 1 | |
# even better | |
from collections import Counter | |
d = Counter(colors) | |
Counter({'green': 3, 'blue': 2, 'red': 1}) | |
# subclass of dict | |
d['yellow'] += 1 | |
Counter({'green': 3, 'blue': 2, 'yellow': 1, 'red': 1}) | |
d.most_common(2) | |
[('green', 3), ('blue', 2)] | |
list(d.elements()) | |
['blue', 'blue', 'green', 'green', 'green', 'yellow', 'red'] | |
# supports also operators +, -, &, |, update |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment