Python Dictionaries

🐍 Python Dictionaries — Full Tutorial

A dictionary in Python is an unordered, changeable, and indexed collection that stores key-value pairs.

  • Keys must be unique and immutable (strings, numbers, tuples).

  • Values can be of any data type.


 1. Creating a Dictionary

# Example 1
student = {"name": "Vipul", "age": 25, "course": "Python"}
# Example 2
employee = dict(name=“Amit”, age=30, dept=“IT”)

# Empty dictionary
empty_dict = {}


 2. Accessing Values

You can access dictionary values by keys:

student = {"name": "Vipul", "age": 25, "course": "Python"}

print(student[“name”]) # Vipul
print(student.get(“age”)) # 25

✅ Using .get() avoids errors if the key does not exist:

print(student.get("salary")) # None

 3. Modifying Dictionary Items

You can update values by key:

student["age"] = 26
student["course"] = "Advanced Python"

Add a new key-value pair:

student["city"] = "Surat"

 4. Removing Items

MethodDescription
pop(key)Removes item with the given key
popitem()Removes the last inserted item
del dict[key]Deletes a key-value pair
clear()Empties the dictionary

Example:

student.pop("course")
del student["city"]
student.clear()

 5. Looping Through Dictionaries

1️⃣ Loop through keys:

for key in student:
print(key)

2️⃣ Loop through values:

for value in student.values():
print(value)

3️⃣ Loop through key-value pairs:

for key, value in student.items():
print(key, ":", value)

 6. Dictionary Methods

MethodDescription
keys()Returns all keys
values()Returns all values
items()Returns all key-value pairs as tuples
copy()Returns a shallow copy
update()Updates dictionary with another dict or key-value pairs

Example:

student.update({"age": 27, "city": "Surat"})
print(student)

 7. Nested Dictionaries

A dictionary can contain other dictionaries:

students = {
"s1": {"name": "Vipul", "age": 25},
"s2": {"name": "Amit", "age": 22}
}
print(students[“s1”][“name”]) # Vipul


 8. Dictionary Comprehension (Advanced)

squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

 9. Checking if a Key Exists

if "name" in student:
print("Name exists!")

10. Merging Dictionaries

Python 3.9+ allows using | operator:

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2
print(merged) # {‘a’: 1, ‘b’: 3, ‘c’: 4}

Or using update():

dict1.update(dict2)
print(dict1)

⭐ Mini Example: Student Info


 


🧠 Summary

FeatureDictionary
Collection TypeKey-value pairs
OrderedPython 3.7+
Mutable✅ Yes
DuplicatesKeys ❌ No, Values ✅ Yes
Accessdict[key] or dict.get(key)

📝 Practice Exercises

  1. Create a dictionary of 3 students with name, age, and course.

  2. Update one student’s age and add a new key city.

  3. Loop through all students and print name and course.

  4. Merge two dictionaries of student marks.

  5. Use dictionary comprehension to create {1:1, 2:4, 3:9, 4:16}.

You may also like...