Suppose we store and retrieve age of Bob and Alice:
ages = [['bob', 23], ['alice',25]]
print(ages[0])
print(ages[0][1])
['bob', 23] 23
Have to remember Bob is index 0 and Alice is index 1
Instead use dictionaries
ages = {'bob': 23, 'alice': 25}
print(ages['bob'])
print(ages['alice'])
23 25
What are dictionaries?
empty_dict = {}
dict1 = {100: 'hundred', 1: 'one', 10: 'ten'}
dict2 = {'bob':['england', -10],
'alice':['england', -5],
'mallory': ['usa',100]}
Dictionaries may be visualised as a mapping from a key to a value.
dict3 = {'a': 'alpha', 'g': 'gamma', 'o':
'omega'}
print(dict1[100])
print(dict2['bob'])
print(dict2['mallory'][1])
hundred ['england', -10] 100
The number of items in a dictionary can be determined using the len() function
len(dict1)
3
Trying to retrieve an item using a key that is not in the dictionary throws an KeyError:
print(dict1)
dict1[1000] # 1000 is not a key
{1: 'one', 10: 'ten', 100: 'hundred'}
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-7-489f939b9cb1> in <module>() 1 print(dict1) ----> 2 dict1[1000] # 1000 is not a key KeyError: 1000
A list of keys in a dictionary can be found using the .keys() member function:
print(dict1.keys())
dict_keys([1, 10, 100])
Likewise, a list of values in a dictionary can be found using the .values() member function:
print(dict1.values())
dict_values(['one', 'ten', 'hundred'])
You can also get both together, using the .items() member function:
print(dict1.items()) # returns a list of tuples
print(dict2.items()) # returns a list of immutable lists
dict_items([(1, 'one'), (10, 'ten'), (100, 'hundred')]) dict_items([('alice', ['england', -5]), ('bob', ['england', -10]), ('mallory', ['usa', 100])])
One can efficiently test if a key is in a dictionary: use the in operator.
print(dict1)
print(100 in dict1)
print(1000 in dict1)
if 100 in dict1:
print('the dictionary contains 100')
{1: 'one', 10: 'ten', 100: 'hundred'} True False the dictionary contains 100
dict1[1000] = 'thousand' # adding item to dict1
print(1000 in dict1) # testing for key
dict2['ezekiel'] = ['france', 50] # adding item to dict2
print(dict2['ezekiel'][0])
print(dict2)
True france {'ezekiel': ['france', 50], 'alice': ['england', -5], 'bob': ['england', -10], 'mallory': ['usa', 100]}
You can add items by using a key that has not been used yet.
Items can be modified from a dictionary just like in a list:
dict2['bob'] = ['england', -5]
print(dict2['bob'])
dict2['bob'][1] = -15
print(dict2['bob'])
['england', -5] ['england', -15]
Similarly, items can be removed from a dictionary using the del operator:
print('mallory' in dict2)
del dict2['mallory']
print('mallory' in dict2)
print(dict2['mallory'])
True False
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-14-ec0a0853e181> in <module>() 2 del dict2['mallory'] 3 print('mallory' in dict2) ----> 4 print(dict2['mallory']) KeyError: 'mallory'
Two common ways of iterating over the items of a dictionary:
for key in dict1:
print(key, dict1[key])
for key, value in dict1.items():
print(key, value)
1000 thousand 1 one 10 ten 100 hundred 1000 thousand 1 one 10 ten 100 hundred
Note that the order in which items are visited in a dictionary is arbitary!
for key, value in dict2.items():
print(key, value)
ezekiel ['france', 50] alice ['england', -5] bob ['england', -15]
Dictionaries are not ordered. List are ordered.
To come...