Dictionary
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.
Creating
{'a':1, 'b':2, 'c':3} # {'a': 1, 'b': 2, 'c': 3}
Creating from other type
dict(['a',1], ['b',2], ['c',3]) # {'a': 1, 'b': 2, 'c': 3}
dict(('a',1), ('b',2), ('c',3)) # {'a': 1, 'b': 2, 'c': 3}
Retrieving from a key
# 1st way
d = {'a':1, 'b':2, 'c':3}
d['a'] # 1
d['z'] # raises KeyError
# 2nd way
d = {'a':1, 'b':2, 'c':3}
d.get('a') # 1
Add a key-value pair
d = {'a':1, 'b':2, 'c':3}
d['d'] = 100
d # {'a': 100, 'b': 2, 'c': 3, 'd': 100}
Replacing an existing value
d = {'a':1, 'b':2, 'c':3}
d['a'] = 100
d # {'a': 100, 'b': 2, 'c': 3}
Replacing multiple existing values
d = {'a':1, 'b':2 }
x = {'a':555, 'z':987}
d.update(x, y=10) # Returns None
d # {'a': 555, 'b': 2, 'y': 10, 'z': 987}
Removing an element
d = {'a':1, 'b':2, 'c':3}
del(d['a'])
d # {'c': 3, 'b': 2}
Getting the keys
d = {'a':1, 'b':2, 'c':3}
d.keys() # ['a', 'c', 'b'] (Python 2)
d.keys() # dict_keys(['a', 'b', 'c']) (Python 3)
Getting the values
d = {'a':1, 'b':2, 'c':3}
d.values() # [1, 2, 3] (Python 2)
d.values() # dict_values([1, 2, 3]) (Python 3)
Iterating over the keys
d = {'a':1, 'b':2, 'c':3}
for k in d:
print("{0}: {1}".format(k, d[k]))
Iterating over the pairs
d = {'a':1, 'b':2, 'c':3}
for k, v in d.items()
print("{0}: {1}".format(k, v)
Iterating over the sorted keys
d = {'a':1, 'b':2, 'c':3}
for k in sorted(d):
print("{0}: {1}".format(k, d[k]))
Find the key with max/min value
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
Check membership
my_dict = {'x':500, 'y':5874, 'z': 560}
print 'x' in my_dict # True
Update frequency
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
Last updated
Was this helpful?