Instagram
youtube
Facebook
Twitter

Common Dictionary Operations

Dictionaries in Python are a built-in data structure that allows us to store a collection of key-value pairs. They are also known as associative arrays or hash maps.

In this tutorial, we will learn about common dictionary operations, including insertion, searching, traversal, and deletion.

Traversing a Dictionary

We can iterate over the keys, values, or key-value pairs of a dictionary using loops with methods like keys(), values(), and items().

Example:

student_scores = {"Rohan":100, "Rohit":80, "Hardik":90, "Aaditya":60}
# Iterating over keys
for student in student_scores.keys():
    print(student)
# Iterating over values
for score in student_scores.values():
    print(score)
# Iterating over key-value pairs
for student, score in student_scores.items():
    print(f'{student}: {score}')

Output:

Rohan
Rohit
Hardik
Aaditya
100
80
90
60
Rohan: 100
Rohit: 80
Hardik: 90
Aaditya: 60

 

Insertion a Dictionary

To add or update an item in a dictionary, we can assign a value to a key. If the key already exists, the value associated with that key will get updated.

Example:

student_scores = {"Rohan":100, "Rohit":80, "Hardik":90, "Aaditya":60}
# Adding a new element
student_scores['Mohak'] = 92
print(student_scores)
# Updating an existing element
student_scores['Rohit'] = 96
print(student_scores)

Output:

{'Rohan': 100, 'Rohit': 80, 'Hardik': 90, 'Aaditya': 60, 'Mohak': 92}
{'Rohan': 100, 'Rohit': 96, 'Hardik': 90, 'Aaditya': 60, 'Mohak': 92}

 

Searching in a Dictionary

We can check if a key exists in a dictionary using the "in" operator. we can also use get() method to retrieve a value.

Example:

student_scores = {"Rohan":100, "Rohit":80, "Hardik":90, "Aaditya":60}
if 'Hardik' in student_scores:
    print(f'Score of Hardik is {student_scores["Hardik"]}')
else:
    print('not in the dictionary')
# Using the get() method to retrieve a value
Rohit_score = student_scores.get('Rohit')  
Rohan_score = student_scores.get('Rohan')  

print(Rohit_score)
print(Rohan_score)

Output:

Score of Hardik is 90
80
100

 

Deletion in a Dictionary

To remove an item from a dictionary, we can use the "del" keyword or the pop() method.

Example:

student_scores = {"Rohan":100, "Rohit":80, "Hardik":90, "Aaditya":60}
# Deleting an item using del
del student_scores['Rohan']
print(student_scores)
# Deleting an item using pop() and providing a default value
removed_score = student_scores.pop('Aaditya')
print(student_scores)

Output:

{'Rohit': 80, 'Hardik': 90, 'Aaditya': 60}
{'Rohit': 80, 'Hardik': 90}