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

  1. Introduction to Dictionaries and checking the type

Code
#input
empty_dict={}
print(type(empty_dict))

#output
<class 'dict'>
  1. Creating the Dictionary

Code
#input
student={"name":"Ram","age":33,"grade":24}
print(student)
print(type(student))

#output
{'name': 'Ram', 'age': 33, 'grade': 24}
<class 'dict'>
  1. 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.

Code
#input
student={"name":"hari","age":32,"name":"Ramu"}
print(student)

#output
{'name': 'Ramu', 'age': 32} #it is taken the last one.
  1. Accessing Dictionary elements with get method

Code
#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
  1. Modify the Dictionary Elements

Code
#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'}
  1. Add the Dictionary Elements

Code
#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'}
  1. Delete the method of the Key and value pair

Code
#input
student={"name":"Ramu","age":32,"grade":'A'}
del student['grade']
print(student)

#output
{'name': 'Ramu', 'age': 33, 'address': 'India'}
  1. Dictionary fetching methods

Code
#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')])
  1. Shallow Copy Methods in Dictionary

Code
#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'}
  1. Iterating over keys in a Dictionary

Code
#input
student={"name":"Ramu","age":32,"grade":'A'}
for keys in student.keys():
    print(keys)

#output
name
age
grade
  1. Iterate over values in a Dictionary

Code
#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

Code
#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
  1. Nested Dictionaries in Python

Code
#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}}
  1. Iterating over nested dictionaries in Python

Code
#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
  1. Merge 2 dictionaries into one in Python

Code
#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}
  1. Create the dictionary: First 10 positive integers using a for loop

Code
#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}
  1. Dictionary with JSON

Code
#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.