Dictionaries

Acknowledgement : the contents of this notebook are partially based on the book "Starting Out with Python (3rd Edition)".

A dictionary is an object that stores a collection of data. Each element in a dictionary has two parts: a key and a value. You use a key to locate a specific value.

Creating a dictionary

dict = {key1:val1, key2:val2, key3:val3}

In [1]:
phonebook = {'Nancy' : '095-276-7826', 'Fern' : '087-123-3476', 'Victoria' : '089-276-2726'}
In [2]:
print(phonebook)
{'Fern': '087-123-3476', 'Nancy': '095-276-7826', 'Victoria': '089-276-2726'}
In [3]:
type(phonebook)
Out[3]:
dict

Retrieving a value from a dictionary

dictionary_name[key]

In [4]:
phonebook['Nancy']
Out[4]:
'095-276-7826'
In [5]:
phonebook['Fern']
Out[5]:
'087-123-3476'
In [6]:
phonebook['Victoria']
Out[6]:
'089-276-2726'
In [7]:
phonebook['Ekasit']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-7-b64db555d5c0> in <module>()
----> 1 phonebook['Ekasit']

KeyError: 'Ekasit'

Using 'in' and 'not in' operators

In [8]:
if 'Nancy' in phonebook:
    print(phonebook['Nancy'])
095-276-7826
In [9]:
if 'Ekasit' in phonebook:
    print(phonebook['Ekasit'])
else:
    print('Not found.')
Not found.

Adding elements to an existing dictionary

Dictionaries are mutable objects.

dictionary_name[key] = value

In [10]:
phonebook['Thubsin'] = '555-555-5555'
In [11]:
print(phonebook)
{'Fern': '087-123-3476', 'Nancy': '095-276-7826', 'Victoria': '089-276-2726', 'Thubsin': '555-555-5555'}
In [12]:
phonebook['Kriangkrai'] = '066-666-6666'
In [13]:
print(phonebook)
{'Kriangkrai': '066-666-6666', 'Fern': '087-123-3476', 'Nancy': '095-276-7826', 'Victoria': '089-276-2726', 'Thubsin': '555-555-5555'}
In [14]:
phonebook['Nancy'] = '099-999-9999'
In [15]:
print(phonebook)
{'Kriangkrai': '066-666-6666', 'Fern': '087-123-3476', 'Nancy': '099-999-9999', 'Victoria': '089-276-2726', 'Thubsin': '555-555-5555'}

Deleting elements

del dictionary_name[key]

In [16]:
print(phonebook)
{'Kriangkrai': '066-666-6666', 'Fern': '087-123-3476', 'Nancy': '099-999-9999', 'Victoria': '089-276-2726', 'Thubsin': '555-555-5555'}
In [17]:
del phonebook['Fern']
In [18]:
print(phonebook)
{'Kriangkrai': '066-666-6666', 'Nancy': '099-999-9999', 'Victoria': '089-276-2726', 'Thubsin': '555-555-5555'}
In [19]:
del phonebook['Ekasit']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-46d625d07bbf> in <module>()
----> 1 del phonebook['Ekasit']

KeyError: 'Ekasit'
In [20]:
if 'Ekasit' in phonebook:
    del phonebook['Ekasit']
else:
    print("Key 'Ekasit' not found.")
Key 'Ekasit' not found.

Getting the number of elements

In [21]:
num_items = len(phonebook)
In [22]:
print(num_items)
4

Mixing data types in a dictionary

In [23]:
test_scores = {'Onkanya':[60,70], 'Ekasit':[65,80], 'Jakrawal':[86,82]}
In [24]:
print(test_scores)
{'Ekasit': [65, 80], 'Onkanya': [60, 70], 'Jakrawal': [86, 82]}
In [25]:
test_scores['Ekasit']
Out[25]:
[65, 80]
In [26]:
test_scores['Onkanya']
Out[26]:
[60, 70]
In [27]:
jakrawal_score = test_scores['Jakrawal']
In [28]:
print(jakrawal_score)
[86, 82]
In [29]:
# different types
mixed_up = {'abc':1, 999:'yada yada', (3, 6, 9):[3, 6, 9]}
In [30]:
mixed_up
Out[30]:
{(3, 6, 9): [3, 6, 9], 999: 'yada yada', 'abc': 1}

Creating an empty dictionary

In [31]:
phonebook = {}
In [32]:
print(phonebook)
{}
In [33]:
phonebook['Krikamol'] = '086-923-5636'
In [34]:
print(phonebook)
{'Krikamol': '086-923-5636'}
In [35]:
phonebook['Tubtim'] = '099-374-7862'
In [36]:
print(phonebook)
{'Krikamol': '086-923-5636', 'Tubtim': '099-374-7862'}
In [37]:
# using dict() function
phonebook = dict()
print(phonebook)
{}
In [38]:
phonebooks = {'krikamol':{'xxx':123,'yyy':456},'Thubsin':{'Kunrob':1234}}
In [39]:
print(phonebooks['Kunrob'])
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-39-d9b5b44d83bb> in <module>()
----> 1 print(phonebooks['Kunrob'])

KeyError: 'Kunrob'

Using for loop to iterate over a dictionary

for var in dictionary:
    statement
    statement
    etc.

In [40]:
phonebook = {'Nancy' : '095-276-7826', 'Fern' : '087-123-3476', 'Victoria' : '089-276-2726'}
In [41]:
for key in phonebook:
    print(key)
Fern
Nancy
Victoria
In [42]:
for key in phonebook:
    print(key,phonebook[key])
Fern 087-123-3476
Nancy 095-276-7826
Victoria 089-276-2726

Some dictionary methods

In [43]:
# clear
# get
# items
# keys
# pop
# popitem
# values
In [44]:
# the clear method : dictionary.clear()

phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333'}
phonebook
Out[44]:
{'Ekasit': '089-333-3333', 'Kanrop': '555-555-8888'}
In [45]:
phonebook.clear()
In [46]:
phonebook
Out[46]:
{}
In [47]:
# the get method : dictionary.get(key,default)
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333'}
value = phonebook.get('Kanrop','Entry not found')
print(value)
555-555-8888
In [48]:
value = phonebook.get('Krikamol','Entry not found')
print(value)
Entry not found
In [49]:
# the items method : phonebook.items()
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333','Thubsin':'123-888-3478'}
value = phonebook.items()
print(value)
dict_items([('Kanrop', '555-555-8888'), ('Ekasit', '089-333-3333'), ('Thubsin', '123-888-3478')])
In [50]:
type(value)
Out[50]:
dict_items
In [51]:
# using for loop with items()
for key, value in phonebook.items():
    print(key,value)
Kanrop 555-555-8888
Ekasit 089-333-3333
Thubsin 123-888-3478
In [52]:
# the key methods : dictionary.keys()
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333','Thubsin':'123-888-3478'}
keys = phonebook.keys()
print(keys)
dict_keys(['Kanrop', 'Ekasit', 'Thubsin'])
In [53]:
# using for loop with keys()
for key in phonebook.keys():
    print(key)
Kanrop
Ekasit
Thubsin
In [54]:
# the pop method : dictionary.pop(key,default)
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333','Thubsin':'123-888-3478'}
In [55]:
phone_num = phonebook.pop('Ekasit','Entry not found')
phone_num
Out[55]:
'089-333-3333'
In [56]:
phonebook
Out[56]:
{'Kanrop': '555-555-8888', 'Thubsin': '123-888-3478'}
In [57]:
phone_num = phonebook.pop('Kanrop','Entry not found')
phone_num
Out[57]:
'555-555-8888'
In [58]:
phonebook
Out[58]:
{'Thubsin': '123-888-3478'}
In [59]:
# the popitem method : k,v = dictionary.popitem()
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333','Thubsin':'123-888-3478'}
phonebook
Out[59]:
{'Ekasit': '089-333-3333', 'Kanrop': '555-555-8888', 'Thubsin': '123-888-3478'}
In [60]:
key, value = phonebook.popitem()
print(key,value)
Kanrop 555-555-8888
In [61]:
phonebook
Out[61]:
{'Ekasit': '089-333-3333', 'Thubsin': '123-888-3478'}
In [62]:
# the values method : dictionary.values()
phonebook = {'Kanrop':'555-555-8888','Ekasit':'089-333-3333','Thubsin':'123-888-3478'}
phonebook.values()
Out[62]:
dict_values(['555-555-8888', '089-333-3333', '123-888-3478'])
In [63]:
# using for with values()
for val in phonebook.values():
    print(val)
555-555-8888
089-333-3333
123-888-3478
In [ ]: