Mutable, unordered pairs (keys and values) of objects. Keys must be hashable.
Advantages: O(1) searching for keys. Makes it easy to create trees and other hierarchical data structures. Can be used to create self-documenting code. Many problems can be described in terms of key-value pairs.
Disadvantages: Only lookup by key. Uses more memory than lists and tuples. Keys must be hashable.
def get_counts(sequence):
counts = {}
for x in sequence:
if x in counts:
counts[x] += 1
else:
counts[x] = 1
return counts
# a easier way
from collections import defaultdict
def get_counts2(sequence):
counts = defaultdict(int) # values will initialize to 0
for x in sequence:
counts[x] += 1
return counts