Dictionary in Python

Dictionary is another built-in data type which allows us to store collection of key-values pairs.

a-dictionary.png

As you can see in the image. Each element in a dictionary has two parts: a key and a value.

Think of Dictionary like a list, unlike list, however, elements stored in the dictionary are not stored in no particular order and we use a key to access a specific value. Most of the time key is a string, but it can be any immutable type such as int, float, tuple, string etc. Each key maps to value, so we can't have duplicate keys. Dictionaries are mutable which means we can add, remove, or update the elements.

Creating Dictionary #

We can create dictionary using the following syntax:

variable_name = {
    'key1' : 'value1',
    'key1' : 'value1',
    ..
    'keyN' : 'valueN',
}

Here is an example:

>>>
>>> contacts = {
...     "tom": "122-444-333",
...     "jim": "412-1231-121",
...     "ron": "8912-121-1212",
...     "jake": "333-1881-121"
... }
>>>
>>>
>>> contacts   
{'jim': '412-1231-121', 'jake': '333-1881-121', 'tom': '122-444-333', 'ron': '89
12-121-1212'}
>>>

This statement creates a dictionary of 4 elements. The key in the first element is "tom" and it's corresponding value is "122-444-333". The rest of the elements are created in the same manner. Although, I have indented each element inside a dictionary, it is not required. It's done here just for the sake of readability.

Note that the order in which elements are displayed in the console is not the same order in which they are created. This shows that the elements in dictionary are stored in no particular order.

To create an empty dictionary do this:

>>>
>>> empty_dict = {}
>>>

Recall from chapter Sets in Python that We also use curly braces ({}) to create sets. As {} creates empty dictionary, to create an empty set use use set() constructor function like this:

>>>
>>> empty_set = set()  # create an empty set
>>> type(empty_set)
<class 'set'>
>>>

We can also use dict() constructor function to create a dictionary object but the syntax is little different. The dict() function require you to pass keyword arguments not the key value pairs separated by colon(:). Here is how we can create the same contacts dictionary using the dict() constructor function.

>>>
>>> dict_contacts = dict(
...    tom = "122-444-333",
...    jim = "412-1231-121",
...    ron = "8912-121-1212",
...    jake = "333-1881-121"
... )
>>>

This statement creates the exact same dictionary. Some people prefer dict() function over curly braces {} because dict() function don't need quotation marks around the keys. Its just a matter of preference, you are free to choose whatever you want. Throughout this guide we will use {} syntax to create dictionaries.

Accessing Value from a Dictionary #

As already discussed order of elements in a dictionary may vary. Consequently, we can't use element index position to access a value in a dictionary. Instead, we use a key. To access value from the dictionary we use the following syntax:

dict_name[key]
>>>
>>> contacts = {
...     "tom": "122-444-333",
...     "jim": "412-1231-121",
...     "ron": "8912-121-1212",
...     "jake": "333-1881-121"
... }
>>>
>>> contacts['ron']
'8912-121-1212'
>>>
>>> contacts['tom']
'122-444-333'
>>>

If the specified key doesn't exists, KeyError exception will be raised.

>>>
>>> contacts['jane']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'jane'
>>>
>>>

Adding and Modifying Values #

We can add new element to a dictionary using the following syntax:

dict_name[key] = value
>>>
>>> contacts['jane'] = '443-123-991'  # add new element
>>>
>>> contacts
{
    'jim': '412-1231-121', 
    'jake': '333-1881-121', 
    'tom': '122-444-333', 
    'jane': '443-123-991', 
    'ron': '8912-121-1212'
}
>>>

If the key already exits in the dictionary, then it's value is updated.

>>>
>>> contacts['jane'] = '443-123-000'  # update Jane's number
>>>
>>> contacts['jane']
'443-123-000'
>>>
>>>

Deleting Elements #

To delete an element from a dictionary, we use the following syntax:

del dict_name[key]
>>>
>>> del contacts['ron']
>>>
>>> contacts
{
    'jim': '412-1231-121', 
    'jake': '333-1881-121', 
    'tom': '122-444-333', 
    'jane': '443-123-000'
}
>>>

If the key doesn't exists in the dictionary, KeyError exception is raised.

>>>
>>> del contacts['ron']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'ron'
>>>

Getting Length of Dictionary using len() #

We can use the built-in len() function to count the number of elements in a dictionary.

>>>
>>> len(contacts)
4
>>>
>>> contacts
{
    'jim': '412-1231-121', 
    'jake': '333-1881-121', 
    'tom': '122-444-333', 
    'jane': '443-123-000'
}
>>>

Iterating through elements using for loop #

We can use for loop to iterate through all the keys in the dictionary as follows:

>>>
>>> for key in contacts:
...   print(key, end=" ")
...
jim jake tom jane >>>
>>>

Once we have a key we can access its corresponding value.

>>>
>>> for key in contacts:
...   print(key, ":" , contacts[key])
...
jim : 412-1231-121
jake : 333-1881-121
tom : 122-444-333
jane : 443-123-000
>>>

Membership Operators with Dictionary #

The in and not in operators can be used to test the existence of a key inside a dictionary. Here are some examples:

>>>
>>> "jane" in contacts   # Does key 'jane' exists in contacts ?
True
>>>
>>> "ron" in contacts   # Does key 'ron' exists in contacts ?
False
>>>
>>> "tom" not in contacts  # Doesn't key 'tom' exists in contacts
False
>>>

Comparision Operators with Dictionary #

We can use == and != operators to test whether two dictionaries contains same elements or not.

>>>
>>> marks1 = { 'larry': 90, 'bill': 60}
>>> marks2 = { 'bill': 60, 'larry': 90}
>>>
>>> marks1 ==  marks2 
True
>>>
>>> marks1 !=  marks2
False
>>>
>>>

The remaining comparison operators such as <, <=, > and >= can't be used with dictionaries because elements in dictionary are stored in not particular order.

Dictionary Methods #

The following table lists some common methods we can call on a dictionary object.

Method Description
keys() Returns a sequence containing only the keys from the dictionary.
values() Returns a sequence containing only the values from the dictionary.
items() Returns a sequence of tuples, where each tuple contains a key and value of an element.
get(key, [default]) Returns the value associated with the key. If the key not found it returns None. We can also provide a optional default value as a second argument in which case if the key is not found, default value will be returned instead of None.
pop(key) Returns the value associated with the key then removes the specified key and it's corresponding value from the dictionary. If key doesn't exists KeyError exception is raised.
popitem() Removes and return a random element from the dictionary as a tuple.
copy() Create a complete copy of the dictionary.
clear() Remove all the elements from the dictionary.

keys() method #

>>>
>>> contacts.keys()
dict_keys(['jim', 'jane', 'tom', 'jake'])
>>>
>>> type(contacts.keys())
<class 'dict_keys'>
>>>

The keys() method returns a sequence of type dict_keys. Think of dict_keys object as a immutable list which you can use in a for loop or pass it's result to other functions for further processing. If you want a list or tuple simply pass the result of keys() method to list() or tuple() constructor as follows:

>>>
>>> list(contacts.keys())
['jim', 'jane', 'tom', 'jake']
>>>
>>> tuple(contacts.keys())
('jim', 'jane', 'tom', 'jake')
>>>
>>>

values() method #

>>>
>>> contacts.values()
dict_values(['412-1231-121', '443-123-000', '122-444-333', '333-1881-121'])
>>>
>>>
>>> type(contacts.values())
<class 'dict_values'>
>>>

>>>
>>> list(contacts.values())
['412-1231-121', '443-123-000', '122-444-333', '333-1881-121']
>>>
>>> tuple(contacts.values())
('412-1231-121', '443-123-000', '122-444-333', '333-1881-121')
>>>
>>>

items() method #

>>>
>>> contacts.items()
dict_items([
    ('jim', '412-1231-121'), 
    ('jane', '443-123-000'), 
    ('tom', '122-444-333'), 
    ('jake', '333-1881-121')
])
>>>

>>>
>>> type(contacts.items())
<class 'dict_items'>
>>>

The items() method returns a sequence of tuples, where each tuple contains key value for an item. We can use a for loop to loop over tuples as follows:

>>>
>>> for k, v in contacts.items():
...    print(key, ":", value)
...
jim : 412-1231-121
jane : 443-123-000
tom : 122-444-333
jake : 333-1881-121
>>>
>>>

Notice that in the for loop we have two target variables key and value, because tuple has two elements. The for loop iterates once for each tuple in the sequence. Each time the loop iterates, the first element(which is a key) is assigned to the variable k and the second element(which is a value) is assigned to the variable v. The process continues until there are elements in the dictionary.

get() method #

>>>
>>> print(contacts.get('jake'))   
333-1881-121
>>>
>>> print(contacts.get('paul'))
None
>>>
>>> print(contacts.get('paul', "Not found"))
Not found
>>>

pop() method #

>>>
>>> contacts
{
    'jim': '412-1231-121', 
    'jane': '443-123-000', 
    'tom': '122-444-333', 
    'jake': '333-1881-121'
}
>>>
>>> contacts.pop('jim')
'412-1231-121'
>>>
>>> contacts
{
    'jane': '443-123-000', 
    'tom': '122-444-333', 
    'jake': '333-1881-121'
}
>>>

>>>
>>> contacts.pop('jim')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'jim'
>>>
>>>

popitem() method #

>>>
>>> contacts.popitem()
('jane', '443-123-000')
>>>
>>> contacts
{'tom': '122-444-333', 'jake': '333-1881-121'}
>>>
>>>

copy() method #

>>>
>>> contacts
{'tom': '122-444-333', 'jake': '333-1881-121'}
>>>
>>> id(contacts)  # address of contacts dictionary
4131208
>>>
>>> copy_contacts = contacts.copy()  # create a copy of the contacts dictionary
>>>
>>> copy_contacts
{'jake': '333-1881-121', 'tom': '122-444-333'}
>>>
>>> id(copy_contacts)   # address of copy_contacts dictionary
4131272
>>>

clear() method #

>>>
>>> contacts.clear()  # delete all the elements
>>>
>>> contacts 
{}
>>>
>>> copy_contacts
{'jake': '333-1881-121', 'tom': '122-444-333'}
>>>
>>>

Although, we have deleted the original contacts dictionary copy_contacts still contains a copy of if it.