Dictionaries in Python

We would have heard of dictionaries in English or other languages. In these we can find meaning for each word. Dictionaries in Python also have a similar concept, where unique keys are mapped to different values.

We will learn dictionaries, accessing and modifying their elements, applying functions and methods, operations on dictionaries, dictionary comprehensions, and nested dictionaries. So let’s start.

Dictionaries in Python

In Python, dictionaries are the data types/ data structures that hold key-value pairs. As said above, these resemble real-world dictionaries. The unique keys are mapped to their corresponding values.

Dictionaries are:

  • Mutable
  • Ordered in Python version 3.7 and not ordered in the earlier versions
  • Dynamic – can add and delete values from a dictionary.
  • Can be nested, a dictionary can have a dictionary as its element. It can also contain any other data types like lists, tuples, etc.
  • It does not allow duplicate keys

How to Create Dictionaries in Python?

Dictionaries are enclosed by the curly brackets ({}) with each key-value pair separated by a comma. And the key and values are related using a colon (:).

The below example shows an example of creating a dictionary and also checking its data type using the function type().

Dictionaries in python example

dict1={}  #creating an empty dictionary
print(f"The type of {dict1} is:{type(dict1)}")

dict2={'name':'abc','age':30, 'gender':'Female'} #creating a dictionary with key-value pairs
print(f"The type of {dict2} is:{type(dict2)}")

Output:

The type of {} is:<class ‘dict’>

The type of {‘name’: ‘abc’, ‘age’: 30, ‘gender’: ‘Female’} is:<class ‘dict’>

Creating Dictionary in Python

1. Python Dictionary with mixed data types:

A dictionary can have keys and values of different data types, including lists, tuples, booleans, keywords, etc.

Example of creating Python dictionary with different data types:

dic1={1:'a','e':[1,2,3],(4,5,6):5}
print(f"The type of {dic1} is:{type(dic1)}")

dic2={1:True,False:0,int:5,5.4:float}
print(f"The type of {dic2} is:{type(dic2)}")

Output:

The type of {1: ‘a’, ‘e’: [1, 2, 3], (4, 5, 6): 5} is:<class ‘dict’>

The type of {1: True, False: 0, <class ‘int’>: 5, 5.4: <class ‘float’>} is:<class ‘dict’>

However, the keys should be immutable data types. So we cannot use a list as a key, because lists are mutable and dictionaries in Python do not allow keys to be changed. We get the following error on using mutable data, like a list, as a key.

Example of getting an error on using a list as a key:

dic1={1:'a',[1,2,3]:3,(4,5,6):5}

Output:

Traceback (most recent call last):
File “<pyshell#30>”, line 1, in <module>
dic1={1:’a’,[1,2,3]:3,(4,5,6):5}
TypeError: unhashable type: ‘list’

2. Using Python dict() function:

Another way to create a dictionary is to use the dict() function, with the set of tuples/lists as arguments or a mapping with curly brackets as shown above. For example,

Example of creating a dictionary using dict():

dic1=dict([[1,'a'],[2,'e'],[3,'i']])
print(f"The type of {dic1} is:{type(dic1)}")

dic2=dict({'a':1,'b':2,'c':3,'d':4,'e':5})
print(f"The type of {dic2} is:{type(dic2)}")

Output:

The type of {1: ‘a’, 2: ‘e’, 3: ‘i’} is:<class ‘dict’>

The type of {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4, ‘e’: 5} is:<class ‘dict’>

It is important to note that while creating the dic1, each of the inner lists has only 2 elements representing the key and the pair respectively.

We are not allowed to give all keys in one list/tuple and all values in another list/tuple. Also, these lists should be the inner elements of a list, else we will get an error. The below example shows this.

Example of getting an error on wrong assigning using dict():

dic1=dict([[1,2,3],['a','e','i']])

dict2=dict([1,'a'],[2,'e'],[3,'i'])

Output:

Traceback (most recent call last):
File “<pyshell#18>”, line 1, in <module>
dic1=dict([[1,2,3],[‘a’,’e’,’i’]])
ValueError: dictionary update sequence element #0 has length 3; 2 is required
Traceback (most recent call last):
File “<pyshell#19>”, line 1, in <module>
dict2=dict([1,’a’],[2,’e’],[3,’i’])
TypeError: dict expected at most 1 argument, got 3

3. Giving duplicate keys in Python

One of the properties of a dictionary is to have unique keys. If we try to use the same key again while creating a dictionary, the new value replaces the old value corresponding to that key. But there is no such restriction on a value. Values can be duplicates.

Example of creating a dictionary using dict():

dic1={'a':1,'b':3,'a':4,'c':3}

print(dic1)

Output:

{‘a’: 4, ‘b’: 3, ‘c’: 3}

We can see that the value corresponding to ‘a’ is 4, which replaced 1. We can also see that ‘b’ and ‘c’ have the same values.

4. Creating an empty dictionary in Python and adding elements:

We can also create an empty dictionary and add key-value pairs to it, to form a dictionary. We can add by using the dictionary name followed by a square bracket with the key and assigning this to the value using ‘=’. For example,

Example of creating Python dictionary by adding elements to an empty one:

dic1={}

dic1[1]='Black'
dic1['a']=1
dic1[(3,4)]=5.4

print(dic1)

Output:

{1: ‘Black’, ‘a’: 1, (3, 4): 5.4}

Accessing elements from a Python Dictionary

Since the elements of a dictionary are not ordered, we cannot use indexing. We can neither use slicing in python using indexes. But we can use the keys to access the values.

1. Accessing the entire Python dictionary:

To access the entire dictionary, we just need the dictionary name. Below is an example.

Example of accessing the entire dictionary in Python

dict1={'name':'xyz','age':15, 'gender':'Male'}
print(dict1)

Output:

{‘name’: ‘xyz’, ‘age’: 15, ‘gender’: ‘Male’}

2. Accessing an element using key in Python:

To access a value from a dictionary we have to use the corresponding key. If we try doing indexing or slicing we get an error. For example,

Example of accessing an element from Python dictionary:

dict1={'name':'xyz','age':15, 'gender':'Male'}
print(dict1['name'])
print(dict1['age'])

print(dict1[1]) #indexing

print(dict1[1:2]) #slicing

Output:

xyz

15

Traceback (most recent call last):
File “<pyshell#64>”, line 1, in <module>
print(dict1[1])
KeyError: 1

Traceback (most recent call last):
File “<pyshell#65>”, line 1, in <module>
print(dict1[1:2])
TypeError: unhashable type: ‘slice’

It doesn’t mean u cannot have the keys resembling the indexes. We can have them as shown below.

Example of accessing an element from a dictionary in Python:

dic1={0:0,1:1,2:4,3:9,4:16,5:25}
dic1[1]

dic1[4]

Output:

1

16

However, we get an error if we try to access using a key that does not exist in the dictionary. For example,

Example of accessing an element from a dictionary:

dic1={1:'a',2:'b',3:'c'}
dic1[5]

Output:

Traceback (most recent call last):
File “<pyshell#59>”, line 1, in <module>
dic1[5]
KeyError: 5

3. Accessing elements using the get() function in Python

We can also access the elements using the get() function. Where we provide the key as an argument and it returns the corresponding value.

Example of accessing an element using Python get():

dic1={'a':1,'b':2,'c':3,'d':4}
dic1.get('c')

Output:

3

Here we do not get an error on giving a nonexisting key as an input to the get() function. It returns None in this case. We can also set a default value as the second argument that is returned if the key is not found. For more understanding, look into the below code.

Example of accessing an element by giving non existing key to the get():

dic1={'a':1,'b':2,'c':3,'d':4}

print(dic1.get('e'))

print(dic1.get('h',-1)) #returning -1 if key not found

Output:

None

-1

4. Accessing inner elements of container values in Python

When we have a container as a value, we can access them first using a key. To access their element, we can use indexing for lists and tuples and keys for dictionaries. For further understanding see the below example.

Example of accessing inner elements:

dic1={1:'a','list':[1,2,3,5],'tup':(5,'s',0.2),'dic':{'a':1.0,'b':2.0}}

dic1['list'][0]  #accessing first element of list

dic1['tup'][2] #accessing third element of tuple

dic1['dic']['a'] #accessing value of key ’a’ of dictionary

Output:

1

0.2

1.0

Modifying Dictionaries in Python

We can reassign a value, add a new key-value pair and also delete a pair in dictionaries. We will see each of them in this section.

1. Reassigning a value

We can reassign a value using the dictionary name followed by the corresponding key in square brackets. And equating it to the new value.

dict_name[key]=new value

Example of reassigning a value in Python.

dict1={'l1':'Python','l2':'Java','l3':'C'}
dict1

dict1['l3']='C++'
dict1

Output:

{‘l1’: ‘Python’, ‘l2’: ‘Java’, ‘l3’: ‘C’}

{‘l1’: ‘Python’, ‘l2’: ‘Java’, ‘l3’: ‘C++’}

2. Adding a new key-value pair in Python

Adding a new element is similar to reassigning, the only difference is that the key does not exist previously in the dictionary.

dict_name[new key]= new value

Example of adding a new pair:

dict1={'l1':'Python','l2':'Java','l3':'C++'}

dict1['l4']='JavaScript'
dict1

dict1['l5']='C#','C'  #Adding a tuple using packing 
dict1

dict1[6]= {1:'SQL',2:'PHP'} #Adding a dictionary
dict1

Output:

{‘l1’: ‘Python’, ‘l2’: ‘Java’, ‘l3’: ‘C++’, ‘l4’: ‘JavaScript’}

{‘l1’: ‘Python’, ‘l2’: ‘Java’, ‘l3’: ‘C++’, ‘l4’: ‘JavaScript’, ‘l5’: (‘C#’, ‘C’)}

{‘l1’: ‘Python’, ‘l2’: ‘Java’, ‘l3’: ‘C++’, ‘l4’: ‘JavaScript’, ‘l5’: (‘C#’, ‘C’), 6: {1: ‘SQL’, 2: ‘PHP’}}

3. Deleting a key-value pair in Python

We can delete a key-value pair using the del keyword. The del can be followed by the dictionary name with the corresponding key in the square brackets.

del dict_name[key]

Example of deleting a key-value pair in Python

dict1={'l1':'Python','l2':'Java','l3':'C++'}

del dict1['l2']
dict1

Output:

{‘l1’: ‘Python’, ‘l3’: ‘C++’}

However, if we try giving the key value that does not exist in the dictionary, then it gives a KeyError as shown below as it could not find a matching key.

Example of getting an error on giving non existing key to delete:

dict1={'l1':'Python','l2':'Java','l3':'C++'}

del dict1['l4']

Output:

Traceback (most recent call last):
File “<pyshell#86>”, line 1, in <module>
del dict1[‘l4’]
KeyError: ‘l4’

4. Deleting entire Python dictionary

We can delete the entire dictionary using the del keyword and the dictionary name. After deleting, the dictionary no longer exists. So, we get a NameError on trying to access it.

Example of deleting a dictionary in Python

dict1={'l1':'Python','l2':'Java','l3':'C++'}

del dict1
dict1

Output:

Traceback (most recent call last):
File “<pyshell#89>”, line 1, in <module>
dict1
NameError: name ‘dict1’ is not defined

Python Built-in Functions

There are many functions that we can apply to dictionaries to get some information without modifying it. We will discuss these functions in this section.

Built-in Functions in Python

1. Python len():

This function is used to find the length of the dictionary, that is the number of key-value pairs. An empty dictionary has a length of 0. An example of finding length is given below.

Example of finding the length of a dictionary in Python

dic1={'abc':1,'xyz':2.5,'pre':3,'lrd':(4,7)}
len(dic1)

Output:

4

2. Python any():

This function is used to check if there is any non-empty/not False/ not 0 key in the dictionary. If the dictionary has at least one non-empty/not False/ not 0 key, it gives True, else False.

Example of using the any() function on Python dictionary:

dict1={'':1,False:'2','t':4}
any(dict1)

dict2={'':1,False:'2',0:4}
any(dict2)

Output:

True

False

3. Python all():

This function is used to check if all the keys are non-empty/not False/ not 0 in the dictionary. It returns True only if all the keys are not empty/not False/ not 0, else False.

Example of using the function all() on dictionary in Python:

dict1={'':1,False:'2','t':4}
all(dict1)

dict2={'a':1,True:'2','t':4}
all(dict2)

Output:

False

True

4. Python sorted():

This gives the sorted version of the dictionary, arranged in ascending order according to the keys. This does not change the original dictionary but returns the keys as a list in sorted order. For example,

Example of using the function all() on the dictionary:

dic1={1:'a',3:'b',7:'4',6.7:'r',5:'d'}

list1=sorted(dic1)
type(list1)

dic1

Output:

<class ‘list’>

{1: ‘a’, 3: ‘b’, 7: ‘4’, 6.7: ‘r’, 5: ‘d’}

However, the keys should be of the same data types for comparison, else we will get an error as shown below.

Example of using the function all() on Python dictionary:

dic1={1:'a','b':3,7:'4',6.7:'r','d':4}
sorted(dic1)

Output:

Traceback (most recent call last):
File “<pyshell#117>”, line 1, in <module>
sorted(dic1)
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’

5. Python cmp():

This function is used to compare the keys and values of two dictionaries. If the dictionaries are equal it gives 0, if the first dictionary is greater then it returns 1 else -1.
This function is not supported in Python3 and the higher versions.

Python Built-in Methods

There are also many built-in methods that we can use on dictionaries to get some information or to modify them. We will discuss this now.

1. Python keys():

This function returns all the keys of the dictionary. The data type of the returned collection of the keys is dict_keys, not any other built-in data structure. The below example shows this.

Example of using the function keys() on Python dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}
dic1.keys()

print(type(dic1.keys()))

Output:

dict_keys([‘a’, ‘e’, ‘i’, ‘o’, ‘u’])

<class ‘dict_keys’>

2. Python values():

This function returns all the keys of the dictionary. The data type of the returned collection of the keys is dict_values, not any other built-in data structure. The below example shows this.

Example of using the function values() on dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

dic1.values()
print(type(dic1.values()))

Output:

dict_values([1, 2, 3, 4, 5])

<class ‘dict_values’>

If two or more values are the same, they will be printed as many times as they occur.

Example of using the function values() on the dictionary with duplicate values:

dic1={'a':1,'e':2,'i':3,'o':2,'u':3}

dic1.values()

Output:

dict_values([1, 2, 3, 2, 3])

3. Python items():

This function returns all the key-value pairs of the dictionary. The data type of the returned collection of the keys is dict_items, not any other built-in data structure. The below example shows this.

Example of using the function items() on dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

dic1.items()

print(type(dic1.items()))

Output:

dict_items([(‘a’, 1), (‘e’, 2), (‘i’, 3), (‘o’, 4), (‘u’, 5)])

<class ‘dict_items’>

4. Python get():

This function is used to find the values of the specified key. If the key does not exist it gives None or the second default value assigned by us if any. For example,

Example of using the function get() on Python dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

dic1.get('o')

print(dic1.get(3))
dic1.get(5.6,-1)

Output:

4

None

-1

5. Python clear():

This function is used to delete all the pairs of the dictionary. It does keep the instance of the dictionary and we get an empty dictionary after clearing. For example,

Example of using the function clear() on Python dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

dic1.clear()
dic1

Output:

{}

6. Python copy():

This function copies all the elements of the dictionary in the new variable and creates new dictionary points in the same memory location. For example,

Example of using copy() Function on Python dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

dic2=dic1.copy()
dic2

Output:

{‘a’: 1, ‘e’: 2, ‘i’: 3, ‘o’: 4, ‘u’: 5}

7. Python pop():

This function is used to delete the key-value pair, given the key as an argument. It can also take a second optional input which is to be returned if the key does not exist in the dictionary.

Example of using the function pop() on dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

dic1.pop('u')

dic1

dic1.pop(4,-1)

Output:

5

{‘a’: 1, ‘e’: 2, ‘i’: 3, ‘o’: 4}

-1

But there is no default value for this function, it gives an error if the key is not found and the 2nd argument is not given. For example,

Example of using the function pop() on dictionary:

dic1.pop(5.9)

Output:

Traceback (most recent call last):
File “<pyshell#20>”, line 1, in <module>
dic1.pop(5.9)
KeyError: 5.9

8. Python popitem():

This function is used to delete the key-value pair at the end of the dictionary. It does not take any argument, just deletes the last element. It returns the key and the value as the elements of a tuple.

Example of using the function popitem() on the dictionary:

dic1={1:'abc',5:'rt','x':5.6,'t':0.4}

dic1.popitem()

dic1.popitem(5)

Output:

(‘t’, 0.4)

Traceback (most recent call last):
File “<pyshell#22>”, line 1, in <module>
dic1.popitem(5)
TypeError: dict.popitem() takes no arguments (1 given)

If we use this function on an empty dictionary, we get an error as there are no elements to delete.
Example of using the function popitem() on an empty dictionary:

dic1={}

dic1.popitem()

Output:

Traceback (most recent call last):
File “<pyshell#43>”, line 2, in <module>
dic1.popitem()
KeyError: ‘popitem(): dictionary is empty’

9. Python fromkeys():

This function is used to create a new dictionary from the given set/tuple of keys. The value can be given as another argument, otherwise, it is None by default. For more understanding look at the following example.

Example of using the function fromkeys() on dictionary:

dic1.fromkeys({0,1,2,3,4})

dic1.fromkeys({0,1,2,3,4},'a')

Output:

{0: None, 1: None, 2: None, 3: None, 4: None}

{0: ‘a’, 1: ‘a’, 2: ‘a’, 3: ‘a’, 4: ‘a’}

10. Python update():

This function is used to add the elements of the second dictionary to the first one. This adds those key-value pairs that are not there in the first dictionary. If the keys are the same but the values are not the same, then the value of the 2nd variable will replace the first one.

Example of using the function update() on dictionary:

dic1={1:'1',2:'2',3:'3'}
dic2={4:'4',3:'3'}

dic1.update(dic2)
dic1

dic3={1:'1',2:'2',3:'3'}
dic4={4:'4',3:'3.0'}

dic3.update(dic4)
dic3

Output:

{1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}

{1: ‘1’, 2: ‘2’, 3: ‘3.0’, 4: ‘4’}

Other methods include:

Method Operation
dic.has_key(key) Returns True if the dictionary contains the key else False
dic.setdefault(key,default=”None”) It is used to set the default as the value to the key, its key is not found in the dictionary
str() Returns a string representation of the dictionary

Operations on Python Dictionaries:

This section covers checking membership and looping through the dictionary.

1. Python Membership Operator:

There are two membership operators, ‘in’ and ‘not in’. These are used to check if a key exists in the dictionary or not. The operator, ‘in’ returns True if it exists or False and ‘not in; does the opposite. For example,

Example of checking membership in Python

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}
'a' in dic1

'r' in dic1

'u' not in dic1

4 not in dic1

Output:

True

False

False

True

2. Python Looping:

We can iterate through the keys of the dictionary using the loops. The below code shows an example of using the for loop for this purpose.

Example of iterating :

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}

for i in dic1:
  print(i)

Output:

a
e
i
o
u

Python Dictionary Comprehensions

Like we have comprehensions for lists, we have them for dictionaries too. These can be used to create dictionaries shortly and efficiently. The syntax is

dict_name ={x:expression(x) for s in iterable}

Following is an example to create a dictionary using dictionary comprehension.

Example of dictionary comprehension in Python:

dic={x:x*2 for x in ['a','b','c','d','e']}
dic

Output:

{‘a’: ‘aa’, ‘b’: ‘bb’, ‘c’: ‘cc’, ‘d’: ‘dd’, ‘e’: ‘ee’}

We can also add conditions to it after the for block inside the brackets as shown below.

Example of dictionary comprehension with condition in Python:

dic={x:x**2 for x in range(10) if x%2==0}
dic

Output:

{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Python Nested Dictionaries

Nested dictionaries are the ones with dictionaries as one/some of the values. An example of creating a nested dictionary and accessing its values using keys is shown below.

Example of creating Python nested dictionary :

dic={1:{2:'a','r':5},4:'t',9.0:5}
dic

dic[1]['r']

Output:

{1: {2: ‘a’, ‘r’: 5}, 4: ‘t’, 9.0: 5}

5

Nested Dictionaries in Python

But we cannot use dictionaries as keys as the values of dictionaries are mutable. It will throw an error as shown below.

Example of getting error on using dictionary as key :

dic={{1:1,2:5}:'p',4:'4.0','o':0}

Output:

Traceback (most recent call last):
File “<pyshell#69>”, line 1, in <module>
dic={{1:1,2:5}:’p’,4:’4.0′,’o’:0}
TypeError: unhashable type: ‘dict’

Interview Questions on Python Dictionaries

1. Write a program to get the next value of the given key in a dictionary?

Ans 1. We can get all the keys and convert them to a list. Then using indexing we can get the next key. Then using the key get the value. The below example finds the next value given the current key as 3.

dic={1:'1',2:'2',3:'3',4:'4',5:'5'}
keys=list(dic.keys())
index=keys.index(3)
key=keys[index+1]
dic[key]

Output:

‘4’

Q2. Write a program to delete an element using popitem, without getting an error if the dictionary is empty.

Ans 2. We can check if the length of the dictionary is zero or not using the len() function and then do the popitem().

Example of deleting elements in Python using popitem:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}
if(len(dic1)):
    dic1.popitem()

dic1

Output:

(‘u’, 5)

{‘a’: 1, ‘e’: 2, ‘i’: 3, ‘o’: 4}

Q3. Write a function to add all the elements of the two dictionaries to the third dictionary.
Ans 3. Below is the example of updating dictionaries in Python

dic1={1:2,2:3}
dic2={2:4,4:5,6:3}
dic3={5:6,3:4,4:7}

dic1.update(dic2)
dic1.update(dic3)

dic1

Output:

{1: 2, 2: 4, 4: 7, 6: 3, 5: 6, 3: 4}

Q4. Write a program to find the sum of all even keys in the dictionary.
Ans 4. We can write for loop and if condition to check if the key is even or not. Below is the Example of looping through the Python dictionary:

dic1={1: 2, 2: 4,3: 4, 4: 7, 5: 6,6: 3}
sum=0
for i in dic1:
    if i%2==0:
        sum=sum+i

    
sum

Output:

12

Q5. Write a program to check if the key is in the dictionary and then add the key-value pair.
Ans 5. We can use the membership operator to check the existence of a key. Below is the Example of checking membership and then adding to the Python dictionary:

dic1={'a':1,'e':2,'i':3,'o':4,'u':5}
key='t'
if(key not in dic1):
    dic1[key]=20
  
dic1

 key='a'
if(key not in dic1):
    dic1[key]=7

dic1

Output:

{‘a’: 1, ‘e’: 2, ‘i’: 3, ‘o’: 4, ‘u’: 5, ‘t’: 20}

{‘a’: 1, ‘e’: 2, ‘i’: 3, ‘o’: 4, ‘u’: 5, ‘t’: 20}

Quiz on Dictionaries in Python

Conclusion

In this write-up, we covered dictionaries, their properties, accessing and modifying the values, methods, functions, and operations. We also covered dictionary comprehensions and nested dictionaries.

Hoping that you understood the topics discussed. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *