Python Dictionaries

A dictionary is a data structure in Python that is unordered, mutable (i.e. modifiable) and indexed. Every element in a dictionary is a key-value pair and is denoted by key : value. Dictionaries are written with curly brackets {}.

Dictionaries are optimized to retrieve values when the keys are known. While values can be of any data type and can be repeated, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

Several operations may be performed on a Python dictionary:~

1) Creation of a dictionary:

To create a dictionary in Python we have to put different comma-separated key-value pairs between curly brackets. It can have any number of elements and they may be of different types. A dictionary may be even empty. It is also possible to use the dict() constructor to create a dictionary. See the code below:

# dict01.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"} # each element is denoted by roll : name
print(student_dict)
mixed_dict = {"Name": "Azad", 100: [10, 20, 30, 40]} # mixed type dictionary
print(mixed_dict)
my_dict = {} # empty dictionary
print(my_dict)
student_dict = dict({101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}) # using dict() constructor
print(student_dict)
student_dict = dict([(101, "Sandip Das"), (102, "Andy Smith"), (103, "Hasan Ali")]) # each element as a pair
print(student_dict)

Output:

{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}
{'Name': 'Azad', 100: [10, 20, 30, 40]}
{}
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}

 

2) Accessing elements of a dictionary:

To access a dictionary element we have to refer to its key name, inside square brackets []. There is also a method called get() that will give the same result. See the code below:

# dict02.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
print(student_dict[102]) # using key to access its corresponding value
print(student_dict.get(102)) # using get() method

Output:

Andy Smith
Andy Smith
 

3) Changing element of a dictionary:

It is easier to change the element of a dictionary using the ‘=’ operator:

# dict03.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
print("Before: ")
print(student_dict)
student_dict[103] = "Raj Singh"
print("After: ")
print(student_dict)

Output:

Before: 
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}
After:
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Raj Singh'}
 

4) Looping through a dictionary:

We can loop through the elements of a dictionary to access the keys and their values:

# dict04.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
# print keys
print("Keys are:~ ")
for t in student_dict:
print(t)
# print values
print("\nValues are: ")
for t in student_dict:
print(student_dict[t])
# alternate way to print values

print("\nValues are:~ ")
for t in student_dict.values(): # using values() method
print(t)
# print key-value pairs
print("\nKeys and Values are:~ ")
for k, v in student_dict.items(): # using items() method
print(k, v)

Output:

Keys are:~ 
101
102
103

Values are:~
Sandip Das
Andy Smith
Hasan Ali

Values are:~
Sandip Das
Andy Smith
Hasan Ali

Keys and Values are:~
101 Sandip Das
102 Andy Smith
103 Hasan Ali

 

5) Length of a dictionary:

It is easier to count the number of elements in a dictionary using the len() method:

# dict05.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
print(len(student_dict))

Output:

3
 

6) To check if an element exists in a dictionary:

To check if an element exists in a dictionary we use the ‘in’ keyword:

# dict06.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
if 101 in student_dict:
print("Yes, 101 is one of the keys in the student dictionary")

Output:

Yes, 101 is one of the keys in the student dictionary
 

7) Add elements to a dictionary:

Dictionary is a mutable data structure. We can add new elements or modify the value of existing elements using assignment operator ‘=’. If the key of an element is already present, its value gets updated, else a new key: value pair is added to the dictionary.

There is a method name update() which inserts the specified elements to the dictionary. The specified elements can be a dictionary, or an iterable object. See the example below:

# dict07.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
student_dict[103] = "Raju Singh" # modifying the existing value
print(student_dict)
# adding new key-value pairs
student_dict[104] = "Rahim Khan"
student_dict[105] = "Ranjan Tata"
print(student_dict)
student_dict.update({106 : "Bikram Ahuja"}) # using update() method
print(student_dict)

Output:

{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Raju Singh'}
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Raju Singh', 104: 'Rahim Khan', 105: 'Ranjan Tata'}
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Raju Singh', 104: 'Rahim Khan', 105: 'Ranjan Tata', 106: 'Bikram Ahuja'}
 

8) Remove elements from a dictionary:

​There are various ​​​methods to remove elements from a dictionary.

Thee pop() method removes element with the specified key name. However, the popitem() method removes the last inserted element. See the example below:

# dict08.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
student_dict.pop(102)
print(student_dict)
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
student_dict.popitem()
print(student_dict)

Output:

{101: 'Sandip Das', 103: 'Hasan Ali'}
{101: 'Sandip Das', 102: 'Andy Smith'}

The ‘del’ keyword deletes the element with the specified key name or can delete the dictionary completely:

# dict09.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
del student_dict[102]
print(student_dict)
del student_dict
# print(student_dict) # will create an error

Output:

{101: 'Sandip Das', 103: 'Hasan Ali'}

The clear() method makes the dictionary empty:

# dict10.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
student_dict.clear()
print(student_dict)

Output:

{}
 

9) Sorting the keys in a dictionary:

We cant sort the keys in a dictionary using the sorted() method:

# dict11.py
student_dict = {101: "Sandip Das", 103: "Hasan Ali", 102: "Andy Smith", 105: "Ranjan Tata", 104: "Bikram Ahuja"}
print(student_dict)
print(sorted(student_dict)) # keys in the dictionary are sorted

Output:

{101: 'Sandip Das', 103: 'Hasan Ali', 102: 'Andy Smith', 105: 'Ranjan Tata', 104: 'Bikram Ahuja'}
[101, 102, 103, 104, 105]
 

10) Copying a dictionary:

It is easier to copy the contents of a dictionary to another using the copy() method:

# dict12.py
student_dict = {101: "Sandip Das", 102: "Andy Smith", 103: "Hasan Ali"}
print(student_dict)
stud_dict = student_dict.copy()
print(stud_dict)

Output:

{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}
{101: 'Sandip Das', 102: 'Andy Smith', 103: 'Hasan Ali'}