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, ...}
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print(student)
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.
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"])
🧠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.
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)
Deleting Dictionary Values
Items in a dictionary can be deleted using the del keyword targeting a specific key.
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)
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
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Keys are :")
for x in student:
print(x)
Printing all the Values
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Values are :")
for x in student:
print(student[x])
Printing Both Keys and Values
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Keys and values are :")
for x, y in student.items():
print(x, y)
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.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Length of Dictionary is:", len(student))
copy()
Returns a shallow copy of the given dictionary.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
student2 = student.copy()
print(student2)
get()
Used to safely get the value of a specified key from the dictionary.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Name is :", student.get("Name"))
print("RegNo is :", student.get("Regno"))
🧠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.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
for x in student.keys():
print(x)
items()
Returns a new view of the dictionary as a collection of key-value tuples.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
for x in student.items():
print(x)
values()
Collects all the values from a dictionary.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
for x in student.values():
print(x)
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.
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)
pop()
Removes the element associated with the specified key and returns its value. If the key isn't present, it throws a KeyError.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
student.pop('Age')
print(student)
student = {"Name": "Kiran", "Regno": 562, "Branch": "CSE"}
# Trying to pop a key that does not exist
student.pop('hallno')
clear()
Used to delete all the items inside the dictionary, leaving it completely empty.
student = {"Name": "Kiran", "Age": 22, "Regno": 562, "Branch": "CSE"}
print("Original:", student)
student.clear()
print("After clear:", student)
0 Comments