Python Dictionary

Comprehensive Guide to Python Dictionaries

1. Creating a Dictionary

A dictionary can be created by using multiple key-value pairs separated by commas , and enclosed within curly braces {}.

Syntax: Dict = {key1: value1, key2: value2, ...}

Python Code - Creating a Dictionary
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}  

print(student)
Output
{'Name': 'Kiran', 'Age': 22, 'Regno': 562, 'Branch': 'CSE'}

2. Accessing Dictionary Values

Data is accessed in lists and tuples using numerical indexing (like [0]). However, values in a dictionary are accessed using their unique keys.

Python Code - Accessing Values via Keys
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}  

print("Name : ", student["Name"])  
print("Age : ", student["Age"])  
print("RegNo : ", student["Regno"])  
print("Branch : ", student["Branch"])
Output
Name : Kiran Age : 22 RegNo : 562 Branch : CSE

🧠 Pop Quiz 1: Dictionary Keys

Question: Can you use a List as a dictionary key? (e.g., {[1, 2]: "Numbers"})

Click here to reveal the answer

Answer: No!

Explanation: Dictionary keys must be immutable. Because lists can be changed after they are created, Python will throw a TypeError: unhashable type: 'list'. You should use a Tuple instead if you need a sequence as a key.

3. Updating and Deleting Values

Updating Dictionary Values

The dictionary is a mutable data type. You can update existing values (or add brand new ones) by assigning a value to a specific key.

Python Code - Updating a Value
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Printing student data .... ")
print(student)

# Update the value associated with the "Name" key
student["Name"] = "Kishore"

print("\nPrinting updated data .... ")
print(student)
Output
Printing student data .... {'Name': 'Kiran', 'Age': 22, 'Regno': 562, 'Branch': 'CSE'} Printing updated data .... {'Name': 'Kishore', 'Age': 22, 'Regno': 562, 'Branch': 'CSE'}

Deleting Dictionary Values

Items in a dictionary can be deleted using the del keyword targeting a specific key.

Python Code - Deleting a Value
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Printing student data .... ")
print(student)

# Delete the "Branch" key-value pair
del student["Branch"]

print("\nPrinting the modified information .... ")  
print(student)
Output
Printing student data .... {'Name': 'Kiran', 'Age': 22, 'Regno': 562, 'Branch': 'CSE'} Printing the modified information .... {'Name': 'Kiran', 'Age': 22, 'Regno': 562}

4. Looping Through Dictionaries

A dictionary can be iterated using a for loop. We can choose to loop through only the keys, only the values, or both simultaneously!

Printing all the Keys

Python Code - Looping Keys
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

print("Keys are :")
for x in student:
    print(x)
Output
Keys are : Name Age Regno Branch

Printing all the Values

Python Code - Looping Values
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

print("Values are :")
for x in student:
    print(student[x])
Output
Values are : Kiran 22 562 CSE

Printing Both Keys and Values

Python Code - Looping Keys & Values
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

print("Keys and values are :")
for x, y in student.items():
    print(x, y)
Output
Keys and values are : Name Kiran Age 22 Regno 562 Branch CSE

5. Built-in Dictionary Functions & Methods

Python provides several highly useful built-in methods specifically designed for dictionaries.

len()

Used to find the total length (number of key-value pairs) of a given dictionary.

Python Code - len()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

print("Length of Dictionary is:", len(student))
Output
Length of Dictionary is: 4

copy()

Returns a shallow copy of the given dictionary.

Python Code - copy()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

student2 = student.copy()
print(student2)
Output
{'Name': 'Kiran', 'Age': 22, 'Regno': 562, 'Branch': 'CSE'}

get()

Used to safely get the value of a specified key from the dictionary.

Python Code - get()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

print("Name is :", student.get("Name"))
print("RegNo is :", student.get("Regno"))
Output
Name is : Kiran RegNo is : 562

🧠 Pop Quiz 2: Bracket vs get()

Question: What is the advantage of using student.get("Email") instead of student["Email"] if the key doesn't exist?

Click here to reveal the answer

Answer: Safety!

Explanation: If you use bracket notation student["Email"] and the key doesn't exist, Python will crash with a KeyError. If you use student.get("Email"), Python will simply return None and your script will keep running.

keys()

Fetches all the keys from the dictionary.

Python Code - keys()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

for x in student.keys():
    print(x)
Output
Name Age Regno Branch

items()

Returns a new view of the dictionary as a collection of key-value tuples.

Python Code - items()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

for x in student.items():
    print(x)
Output
('Name', 'Kiran') ('Age', 22) ('Regno', 562) ('Branch', 'CSE')

values()

Collects all the values from a dictionary.

Python Code - values()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

for x in student.values():
    print(x)
Output
Kiran 22 562 CSE

update()

Updates the dictionary with the provided key-value pairs. It inserts the key/value if it is not present, or overwrites the value if the key already exists.

Python Code - update()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

# Overwriting an existing key
student.update({"Regno": 590})

# Adding a brand new key
student.update({"phno": 56895})

print(student)
Output
{'Name': 'Kiran', 'Age': 22, 'Regno': 590, 'Branch': 'CSE', 'phno': 56895}

pop()

Removes the element associated with the specified key and returns its value. If the key isn't present, it throws a KeyError.

Python Code - pop() Existing Key
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}

student.pop('Age')
print(student)
Output
{'Name': 'Kiran', 'Regno': 562, 'Branch': 'CSE'}
Python Code - pop() Missing Key
student = {"Name": "Kiran", "Regno": 562, "Branch": "CSE"}

# Trying to pop a key that does not exist
student.pop('hallno')
Output
KeyError: 'hallno'

clear()

Used to delete all the items inside the dictionary, leaving it completely empty.

Python Code - clear()
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Original:", student)

student.clear()
print("After clear:", student)
Output
Original: {'Name': 'Kiran', 'Age': 22, 'Regno': 562, 'Branch': 'CSE'} After clear: {}

Post a Comment

0 Comments