In the last session, we discussed the sets. Now, we will look at Python's Dictionary Operations. The sets are the most important topic in Python.
Let’s start,
Definition of Dictionary in Python
A dictionary is an unordered and changeable collection of key–value pairs.
Each key in a dictionary is unique and is used to identify its corresponding value.
The values can repeat and can be of any data type.
Dictionaries allow fast access, insertion, and deletion of data using keys.
Duplicate keys are not allowed; if the same key appears more than once, the last value replaces the previous one.
Dictionaries is enclosed with curly braces { }
Introduction to Dictionaries and checking the type
#input
empty_dict={}
print(type(empty_dict))
#output
<class 'dict'>
Creating the Dictionary
#input
student={"name":"Ram","age":33,"grade":24}
print(student)
print(type(student))
#output
{'name': 'Ram', 'age': 33, 'grade': 24}
<class 'dict'>
A single key is always used; it is not allowed to have duplicates. If more than one key is present in the dictionary, it chooses the last one.
#input
student={"name":"hari","age":32,"name":"Ramu"}
print(student)
#output
{'name': 'Ramu', 'age': 32} #it is taken the last one.
Accessing Dictionary elements with get method
#input
student={"name":"Ramu","age":32,"grade":'A'}
print(student['grade'])
print(student['age'])
## Accessing using get() method
print(student.get('grade'))
print(student.get('last_name'))
print(student.get('last_name',"Not Available"))
#output
A
32
A
None #in that given dictionary last_name not present
Not Available
Modify the Dictionary Elements
#input
student={"name":"Ramu","age":32,"grade":'A'}
student["age"]=33 ##update value for the key
print(student)
#output
{'name': 'Ramu', 'age': 33, 'grade': 'A'}
Add the Dictionary Elements
#input
student={"name":"Ramu","age":32,"grade":'A'}
student["address"]="India" ## added a new key and value
print(student)
#output
{'name': 'Ramu', 'age': 33, 'grade': 'A', 'address': 'India'}
Delete the method of the Key and value pair
#input
student={"name":"Ramu","age":32,"grade":'A'}
del student['grade']
print(student)
#output
{'name': 'Ramu', 'age': 33, 'address': 'India'}
Dictionary fetching methods
#input
student={"name":"Ramu","age":32,"grade":'A'}
keys=student.keys() ##get all the keys
print(keys)
values=student.values() ##get all values
print(values)
items=student.items() ##get all key value pairs
print(items)
#output
dict_keys(['name', 'age', 'address'])
dict_values(['Ramu', 33, 'India'])
dict_items([('name', 'Ramu'), ('age', 33), ('address', 'India')])
Shallow Copy Methods in Dictionary
#input
student={"name":"Ramu","age":32,"grade":'A'}
student_copy1=student.copy() ## shallow copy
print("Before Shallow Copy")
print(student_copy1)
print(student)
print("After Shallow Copy")
student["name"]="Hari"
print(student_copy1)
print(student)
#output
Before Shallow Copy
{'name': 'Ramu', 'age': 32, 'grade': 'A'}
{'name': 'Ramu', 'age': 32, 'grade': 'A'}
After Shallow Copy
{'name': 'Ramu', 'age': 32, 'grade': 'A'}
{'name': 'Hari', 'age': 32, 'grade': 'A'}
Iterating over keys in a Dictionary
#input
student={"name":"Ramu","age":32,"grade":'A'}
for keys in student.keys():
print(keys)
#output
name
age
grade
Iterate over values in a Dictionary
#input
student={"name":"Ramu","age":32,"grade":'A'}
for value in student.values():
print(value)
#output
Ramu
32
A
12. Iterate over key-value pairs
#input
student={"name":"Ramu","age":32,"grade":'A'}
for key,value in student.items():
print(f"{key}:{value}")
#output
name:KRish3
age:32
grade:A
Nested Dictionaries in Python
#input
students={
"student1":{"name":"Raj","age":32},
"student2":{"name":"Vijay","age":35}
}
print(students)
#output
{'student1': {'name': 'Raj', 'age': 32}, 'student2': {'name': 'Vijay', 'age': 35}}
Iterating over nested dictionaries in Python
#input
for student_id,student_info in students.items():
print(f"{student_id}:{student_info}")
for key,value in student_info.items():
print(f"{key}:{value}")
#output
student1:{'name': 'Raj', 'age': 32}
name:Raj
age:32
student2:{'name': 'Vijay', 'age': 35}
name:Vijay
age:35
Merge 2 dictionaries into one in Python
#input
dict1={"a":1,"b":2}
dict2={"c":3,"d":4}
merged_dict={**dict1,**dict2}
print(merged_dict)
#output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Create the dictionary: First 10 positive integers using a for loop
#input
d = {i: i**2 for i in range(1, 11)}
print(d)
#output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Dictionary with JSON
#input
import json
book = {
'title': 'Ponniyin Selvan',
'author': 'Kalki Krishnamurthy',
'year': 1955,
'genre': 'Historical Fiction'
}
book_json = json.dumps(book)
print(book_json)
#output
{"title": "Ponniyin Selvan", "author": "Kalki Krishnamurthy", "year": 1955, "genre": "Historical Fiction"}
Now, We have covered Dictionary operations with various examples and methods. In the next article, we will dive into Functions in Python.