poros
10/4/2015 - 4:03 PM

Counting with dictionaries

Counting with dictionaries

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