Dictionaries in Python

In this tutorial, we will discuss about dictionary datatype in python, different operations on dictionaries and built-in methods available for dictionaries.

Dictionaries in Python

In python, dictionaries is an unordered collection of items. Each item of the dictionary is in the form of key:value pair. Python views a dictionary as a mapping between keys and values.

Creating a Dictionary

A dictionary is an unordered collection of arbitrary python objects as keys and values.

The key and value pairs are written as key : value key and value are separated using colon ( : ), multiple key value pairs separated by commas and enclosed within curly braces ( { } )

Dictionaries are also known as associative arrays or mappings or hashes.

Following is an example of a simple dictionary :

Dict1 = { 1 : 'a', 2 : 'b', 3 : 'c' }

Following table shows different types of dictionary declarations in python.

Expression Description
D1 = { } Empty dictionary
D2 = { 1 : 'a' , 2 : 'b', 3 : 'c'} Simple declaration of a dictionary
D3 = { 1 : 'a', 2 : { 'b' : 'cde' , 3 : 456 }} Nested dictionary
D4 = dict(name='Rishi', age=23 ) Using dict() constructor
D5 = dict( [ ['name', 'rishi'], ['age', 21] ] ) Using dict() constructor with sequences of key:value pairs
D6 = dict.fromkeys([1, 2], 'a') Using fromkeys() method
D7 = dict( zip( ('a','b','c'), (1,2,3) ) ) Using zip() method with dict() constructor

The first 2 declarations are pretty straight forward, first one is an empty dictionary and second one is the simple dictionary declaration.

The third expression is a nested dictionary which means there is a dictionary inside a dictionary.

The fourth declaration shows how we can create a dictionary using dict() constructor in python.

The fifth and sixth declaration also used dict constructor but it uses dict.fromkeys() and zip() methods with that.

Let's see some examples on creating a dictionary in python.

Dict1 = { 1 : 'a', 2 : { 'b' : 'cde' , 3 : 456 }}
print("Nested Dictionary : ", Dict1)
print("Accessing an element from dictionary inside a dictionary : Dict1[2][3] - ", Dict1[2][3] )
Dict2 = dict(name='Raj', age=21)
print("Dictionary using dict() constructor : ",Dict2)
Dict3 = dict( [ ['a',1], ['b',2], ['c',3] ] )
print("Dictionary using dict() constructor with separate sequences for key:value pairs : ", Dict3)
Dict4 = dict.fromkeys([1,2], 'a')
print("Dictionary using fromkeys() method : ",Dict4)
Dict5 = dict(zip( (1,2,3), ('a','b','c') ) )
print("Dictionary using zip() method : ",Dict5)
Nested Dictionary :  {1: 'a', 2: {'b': 'cde', 3: 456}}
Accessing an element from dictionary inside a dictionary : Dict1[2][3] -  456
Dictionary using dict() constructor :  {'name': 'Raj', 'age': 21}
Dictionary using dict() constructor with separate sequences for key:value pairs :  {'a': 1, 'b': 2, 'c': 3}
Dictionary using fromkeys() method :  {1: 'a', 2: 'a'}
Dictionary using zip() method :  {1: 'a', 2: 'b', 3: 'c'}

The dictionaries are indexed using keys internally. While creating a dictionary make sure that you use only immutable python object types like string, number or tuple with immutable elements as keys.

If we use mutable type as keys then we will get TypeError as shown below:

Dct = { [1,2] : 'sf', 2 : 3}
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

< ipython-input-36-7943b1a2ff01 > in < module >
----> 1 Dct = { [1,2] : 'sf', 2 : 3}

TypeError: unhashable type: 'list'

The TypeError : unhashable type means that we have tried to assign a key with a mutable type and this is not allowed in python.

Accessing Elements in a Dictionary

Dictionaries in python are unordered collections, so elements of a dictionary cannot be accessed using indices.

To access an element of a dictionary, we would require the key. Using the key we can get value corresponding to that key in a dictionary.

Accessing a value from a dictionary using the corresponding key is also called as look-up operation.

Let's see how do we access a value from a dictionary in python:

Dct1 = {1 : 'a', 2 : 'b', 3 : 'c', 4 : { 'd': 5, 'e' : 6 , 7 : 'fg'}}
print("Dictionary : ", Dct1)
print("Dct1[2] = ",Dct1[2])
print("Dct1[4]['e'] = ",Dct1[4]['e'])  # Accessing nested dictionary values.
Dictionary :  {1: 'a', 2: 'b', 3: 'c', 4: {'d': 5, 'e': 6, 7: 'fg'}}
Dct1[2] =  b
Dct1[4]['e'] =  6

So, if we want to access any element of a dictionary we would require the key to access that value.

Let's see what will happen if we access a key that is not present.

print(Dct1[5])
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

< ipython-input-41-3900eebe9aa5 > in < module >
----> 1 print(Dct1[5])

KeyError: 5

Python throws KeyError means that the key we are trying to access does not exist in the dictionary.

Accessing only Keys and Values :

As we need to have a key to access a value, it is difficult to remember every key present in a dictionary.

In python, we have methods that gives us all the keys and all the values of a dictionary. These methods are keys() and values().

Let's see how do we use them :

Dct2 = {'v1' : 'a', 'v2' : 'e', 'v3' : 'i', 'v4' : 'o', 'v5' : 'u' }
print(Dct2.keys())
print(Dct2.values())
dict_keys(['v1', 'v2', 'v3', 'v4', 'v5'])
dict_values(['a', 'e', 'i', 'o', 'u'])

As we can see keys() method returns all the keys in a dictionary and values() returns all the values of a dictionary.

Using this method we get a sequence containing all the keys and all the values of a dictionary.

We can use list() constructor to convert the output of these methods into a list sequence as shown in below example.

L1 = list(Dct1.keys())
print(L1)
print(list(Dct1.values()))
[1, 2, 3, 4]
['a', 'b', 'c', {'d': 5, 'e': 6, 7: 'fg'}]

Observe the change in output of the print statement. And using this way it will be easier to handle the list of keys and values of a dictionary.

Traversing through a Dictionary

As we know, traversing means accessing and processing each and every element of a sequence with help of loops.

However, dictionary is a mapping but we can traverse or iterate through a dictionary as shown on the following example :

print("Dictionary : ",Dct2)
print("Traversing through the dictionary : ")
for val in Dct2 :
    print(val, " : ",Dct2[val])
Dictionary :  {'v1': 'a', 'v2': 'e', 'v3': 'i', 'v4': 'o', 'v5': 'u'}
Traversing through the dictionary : 
v1  :  a
v2  :  e
v3  :  i
v4  :  o
v5  :  u

We can also used keys() method or values() method for iterating through keys or values of a dictionary. Let's see how :

for val1 in Dct2.keys() :
    print(val1)
v1
v2
v3
v4
v5
for val1 in Dct2.values() :
    print(val1)
a
e
i
o
u

Properties of Dictionary

We have seen creating, accessing and traversing a dictionary but before we go ahead let's look at some important points about dictionaries which will be useful when you work with them.

  1. Unordered collection : A dictionary in python is an unordered collection which means that the order of key:value pairs in dictionary is not fixed. That is why we require keys to access corresponding values from a dictionary.

Note : In python version 3.7 dictionaries are ordered which means key : value pairs are at the same position as they are added. Even though dictionary is ordered, we are able to access values only using the keys present inside a dictionary.

In python version 3.6 and earlier dictionaries are unordered.

  1. Keys must be Unique : All the keys inside a dictionary must be unique. There might be same values assigned to other keys but if we have same keys with different values then only the last/latest value assigned to that key is considered.

Let's see an example :

Dct2 = {"Apple" : 5, "Orange" : 8, "Guava" : 4, "Banana" : 4, "Apple" : 12}
print(Dct2)
print('Dct2["Apple"] - ',Dct2["Apple"])
{'Apple': 12, 'Orange': 8, 'Guava': 4, 'Banana': 4}
Dct2["Apple"] -  12

So, make sure that all keys of a dictionary should always be unique.

  1. Dictionaries are Mutable : Even though the keys of a dictionary should only be immutable objects but dictionary in itself is a mutable python object. This means that we can modify value of a key in a dictionary, add a new key : value pair to a dictionary and delete a key:value pair from a dictionary.

  2. Stored as Mapping : Internally, dictionaries are stored as mappings. The key value pairs from a dictionary are associated with each other using some internal function (known as hash function). This linking between keys and values is also called mapping.

Dictionary Methods in Python

Python also provides built-in methods for dictionary manipulation which help us process and manipulate dictionary more easily.

Following is a list of methods provided in python for list manipulation along with small description about each of them.

Method() Description
clear() Removes all items from the dictionary
copy() Returns a true copy of the dictionary
fromkeys() Returns a new dictionary with keys and values as argument
key() Returns the value of key given as argument
items() Returns a sequence containing (key,value) pairs of the dictionary
keys() Returns a sequence of all keys of the dictionary
values() Returns a sequence of all values of the dictionary
pop() Removes and returns a value for the passed key
popitem() Removes and returns a key:value pair from dictionary
setdefault() Inserts a new element if key does not exist else returns value of the existing key
update() Appends the elements of dictionary in argument to original dictionary

Some examples of Python dictionary methods :

Marks = {'Asha': 68.35, 'Divya': 78.97, 'Harsh': 53.85}
print("items() method : ", Marks.items() )
Marks.update({'Asha' : 76.83, 'Manish' : 74.46, 'Jui': 62.53})
print("update() method : ", Marks )
print("pop() method : ", Marks.pop('Jui'))
print(Marks)
print("setdefault() method : ", Marks.setdefault('Raj',78.72))
print(Marks)
items() method :  dict_items([('Asha', 68.35), ('Divya', 78.97), ('Harsh', 53.85)])
update() method :  {'Asha': 76.83, 'Divya': 78.97, 'Harsh': 53.85, 'Manish': 74.46, 'Jui': 62.53}
pop() method :  62.53
{'Asha': 76.83, 'Divya': 78.97, 'Harsh': 53.85, 'Manish': 74.46}
setdefault() method :  78.72
{'Asha': 76.83, 'Divya': 78.97, 'Harsh': 53.85, 'Manish': 74.46, 'Raj': 78.72}

We will learn about these functions as we learn in further articles with more examples.

Working with Dictionaries

Until now, we have seen creating a dictionary, accessing elements of dictionary, traversing through a dictionary, properties of dictionary and built-in methods available for dictionary.

Let's move ahead and learn about adding elements to a dictionary, updating and deleting elements from a dictionary and other manipulations we can do with dictionaries.

Adding elements to Dictionary

Adding an element to a dictionary means adding a key:value pair to a dictionary.

We can add a new key : value pair to a dictionary using simple assignment statement.

We have to make sure that the key we are using is unique and is not already present in the dictionary otherwise we will overwrite value of already existing key and lose the data.

Let's see some examples :

Fruits = {"Apple" : 10, "Orange" : 8, "Guava" : 6, "Banana" : 4 }
print("Original dictionary : ", Fruits)
Fruits['Coconut'] = 5
print("After adding new element : ", Fruits )
Original dictionary :  {'Apple': 10, 'Orange': 8, 'Guava': 6, 'Banana': 4}
After adding new element :  {'Apple': 10, 'Orange': 8, 'Guava': 6, 'Banana': 4, 'Coconut': 5}

Another way of adding elements to a dictionary is using built-in methods update() and setdefault().

  • update() method : It takes a dictionary as an argument and updates the original dictionary. If key is common in argument dictionary and original dictionary then it will update the existing key with new values. Otherwise it will append the key: value pairs from argument dictionary to the original dictionary.

  • setdefault() method : It takes two arguments first is key and second is the value to that key. If the key is not present in the original dictionary then it will add the key:value pair to the dictionary and return the value. Otherwise if the key already exists then it will return the original value for that key and will not change the original dictionary.

Let's see some examples of update() and setdefault() :

Dct = {1:'a', 2:'b', 3:'c'}
print("Original dictionary : ",Dct)
Dct.update({3:'d', 4:'e'})
print("Aftr update() method : ", Dct)
print("Setdefault unique key : ",Dct.setdefault(5,'f'))
print("Setdefault existing key : ",Dct.setdefault(4,'g'))
print("After setdefault() method : ",Dct)
Original dictionary :  {1: 'a', 2: 'b', 3: 'c'}
Aftr update() method :  {1: 'a', 2: 'b', 3: 'd', 4: 'e'}
Setdefault unique key :  f
Setdefault existing key :  e
After setdefault() method :  {1: 'a', 2: 'b', 3: 'd', 4: 'e', 5: 'f'}

Modifying elements in a Dictionary

As you know, dictionary is a mutable object so we are able to modify the values of an existing element in a dictionary.

Note that we can only modify values of an existing key and not the other way round.

Modifying an existing element is also done using an assignment statement just like adding a new element.

The difference is that for modifying an existing element we need to make sure that the key we are using is already present inside the dictionary.

Let's see some examples :

print("Original dictionary : ", Fruits)
print("Original Dct2['Apple'] = ",Fruits['Apple'])
Fruits['Apple'] = 3
print("After changing Dct2['Apple'] = ",Fruits['Apple'])
print("After modifying the element : ", Fruits )
Original dictionary :  {'Apple': 5, 'Orange': 8, 'Guava': 6, 'Banana': 4, 'Coconut': 5}
Original Dct2['Apple'] =  5
After changing Dct2['Apple'] =  3
After modifying the element :  {'Apple': 3, 'Orange': 8, 'Guava': 6, 'Banana': 4, 'Coconut': 5}

Deleting Elements from a Dictionary

As dictionary is mutable, we are also able to delete specific elements from a dictionary using del operator, pop() and popitem() methods. Let's learn about them one by one :

1. del operator

Python provides del operator to delete a specific key:value pair from the dictionary. Syntax of using del operator with dictionary is as follows :

del dict[ key ]

If the key given to del operator is not present in the dictionary then it will throw KeyError. Let's see an example :

print("Dictionary : ",Fruits)
del Fruits['Apple']
print("After deleting : ",Fruits)
del Fruits['Melon']
Dictionary :  {'Apple': 3, 'Orange': 8, 'Guava': 6, 'Banana': 4, 'Coconut': 5}
After deleting :  {'Orange': 8, 'Guava': 6, 'Banana': 4, 'Coconut': 5}

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

< ipython-input-102-815a500b2d12 > in < module >
      2 del Fruits['Apple']
      3 print("After deleting : ",Fruits)
----> 4 del Fruits['Melon']

KeyError: 'Melon'

2. pop( ) method

The pop() method is a built-in method for dictionaries which take a key as an argument. It returns the value corresponding to key in argument and removes a key:value pair from the dictionary.

Let's see how pop() method works :

print("Dictionary : ",Fruits)
print("pop() method : ", Fruits.pop('Guava'))
print("After pop() method : ", Fruits)
Dictionary :  {'Orange': 8, 'Guava': 6, 'Banana': 4, 'Coconut': 5}
pop() method :  6
After pop() method :  {'Orange': 8, 'Banana': 4, 'Coconut': 5}

3. popitem() method

The popitem() method is a built-in method for dictionaries which returns and removes the last key:value pair from the dictionary. If the dictionary is empty then it will throw KeyError.

Let's see how popitem() method works :

d = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
print(d.popitem())
(5, 'e')

Membership Operation

Just like strings, lists and tuples support membership operators in and not in the dictionaries also support membership operators.

These operators are used to check if given key is present in the dictionary.

Let's see use of these operators with dictionary in python.

dict1 = {1:'a', 2:'b', 3:'c'}
print( 1 in dict1 )
True
print( 2 not in dict1 )
False

Dictionary Comprehension

In python, you can also create a dictionary using dictionary comprehension. To create a dictionary using this way, we have to type an expression followed by a for loop statement all inside a square bracket.

Following is an example showing use of dictionary comprehension.

squar = {i : i*i for i in range(1,6)}
print(squar)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

We can also add an if statement to filter out the output of for statement.

Following is an example of dictionary comprehension with if statement.

squar2 = {i : i*i for i in range(1,21) if i%3==0}
print(squar2)
{3: 9, 6: 36, 9: 81, 12: 144, 15: 225, 18: 324}

Conclusion

In this tutorial, we have discussed about dictionary datatype in python. Creating and accessing elements of a dictionary, built-in methods for dictionary and dictionary manipulations in python.

If you have any questions please comment below also share your views and suggestions in the comment box.

Pooja is a programmer by profession and love to write articles on Python. She is highly interested in Python, Data Science and Machine Learning. Pooja holds B.E. Computer Engineering degree. She loves teaching and learning new thing.

Leave a Comment