This tutorial provides a complete and detailed explanation of Python dictionaries, how they work internally, how to create, access, update, and delete elements, and how dictionaries behave in real-world programs. The structure follows the same format as your earlier Python tutorials on int, float, complex, typecasting, and immutability.
1. Introduction to Python Dictionaries
A dictionary in Python is a built-in data structure used to store data in the form of key–value pairs. A key represents what you want to search, and the value is the information associated with that key.
Dictionaries are:
• Mutable
• Unordered (conceptually; Python preserves insertion order as of 3.7)
• Dynamically resizable
• Based on hash tables
A dictionary gives average O(1) access time for lookup, insertion, and deletion, making it one of the most efficient Python data types for structured data.
2. Basic Structure of a Dictionary
The syntax of a dictionary is:
{
key1: value1,
key2: value2,
key3: value3
}
Properties:
• A key must be unique.
• A key must be immutable (str, int, float, tuple).
• A value can be any Python object.
Example:
student = {
"name": "Samir",
"age": 63,
"city": "Mumbai"
}
3. Creating Dictionaries
Python allows multiple ways to construct dictionaries.
3.1 Using Curly Braces
person = {"name": "Samir", "age": 63}
3.2 Using dict() Constructor
person = dict(name="Samir", age=63)
3.3 Creating an Empty Dictionary
d = {}
3.4 Adding Values After Creation
d = {}
d["language"] = "Python"
d["version"] = 3.12
3.5 From List of Tuples
pairs = [("a", 1), ("b", 2)]
d = dict(pairs)
3.6 Dictionary Comprehension
squares = {x: x*x for x in range(1, 6)}
4. Accessing Dictionary Elements
4.1 Access Using Key
student["name"]
If the key does not exist, Python raises a KeyError.
4.2 Using get() Method
student.get("name")
student.get("salary", 0) # returns default value 0 if key not found
Using get() is safer because it avoids KeyError.
4.3 Membership Test
"name" in student
This checks whether a key exists in the dictionary.
5. Updating Dictionary Values
5.1 Changing a Value
student["age"] = 64
5.2 Adding New Key–Value Pair
student["email"] = "samir@example.com"
5.3 update() Method
This method can add or modify multiple key–value pairs.
student.update({"age": 65, "city": "Pune"})
6. Removing Elements from Dictionary
6.1 Using pop()
student.pop("city")
Removes key and returns its value.
6.2 Using popitem()
student.popitem()
Removes the last inserted key–value pair.
6.3 Using del Statement
del student["age"]
6.4 Clearing Entire Dictionary
student.clear()
7. Dictionary Views (keys, values, items)
Python provides special view objects that reflect dictionary content dynamically.
student.keys() student.values() student.items()
These can be used for iteration, processing, and transformations.
8. Looping Through Dictionaries
8.1 Looping Through Keys
for key in student:
print(key)
8.2 Looping Through Values
for value in student.values():
print(value)
8.3 Looping Through Key–Value Pairs
for key, value in student.items():
print(key, value)
9. Nested Dictionaries
Dictionaries can contain other dictionaries, forming complex structured data.
Example:
employee = {
"id": 101,
"name": "Samir",
"address": {
"city": "Mumbai",
"pin": 400001,
"country": "India"
},
"skills": ["Python", "React", "Spring Boot"]
}
Accessing nested data:
employee["address"]["city"] employee["skills"][0]
Updating nested values:
employee["address"]["pin"] = 400002
10. Mutability Rules for Dictionaries
Keys must be immutable because they are hashed. Valid keys include:
• strings
• integers
• floats
• tuples containing only immutable items
Invalid key types:
• list
• set
• dictionary
Values can be mutable:
d = {"numbers": [1, 2, 3]}
d["numbers"].append(4)
11. Copying Dictionaries
11.1 Shallow Copy
copy1 = student.copy() copy2 = dict(student)
11.2 Deep Copy
Used for nested dictionaries.
import copy deep_copy = copy.deepcopy(employee)
12. Important Dictionary Methods with Examples
12.1 setdefault()
d = {}
d.setdefault("languages", []).append("Python")
12.2 fromkeys()
keys = ["a", "b", "c"] new_dict = dict.fromkeys(keys, 0)
12.3 pop() and popitem()
Already explained above.
13. How Dictionaries Work Internally
Dictionaries are built on hash tables.
Steps when inserting a key–value pair:
- Python calculates a hash value using the key’s hash function.
- The hash determines the location in the hash table.
- If an index is occupied, Python uses open addressing to resolve collision.
- Dictionary dynamically resizes when load factor increases.
Time complexity:
• Lookup: O(1) average
• Insert: O(1) average
• Delete: O(1) average
14. Dictionary Comprehension
14.1 Simple Comprehension
squares = {x: x*x for x in range(1, 6)}
14.2 Filtered Dictionary
even_squares = {x: x*x for x in range(1, 11) if x % 2 == 0}
14.3 Using zip()
keys = ["name", "age", "city"]
values = ["Samir", 63, "Mumbai"]
combined = {k: v for k, v in zip(keys, values)}
15. Practical Examples
15.1 Counting Word Frequency
text = "python dict tutorial python tutorial"
freq = {}
for word in text.split():
freq[word] = freq.get(word, 0) + 1
15.2 JSON-Like Object
user = {
"id": 1,
"username": "samir",
"roles": ["admin", "user"],
"profile": {
"city": "Mumbai",
"level": 5
}
}
15.3 Dictionary as Switch-Case
def day_name(n):
mapping = {
1: "Monday",
2: "Tuesday",
3: "Wednesday"
}
return mapping.get(n, "Invalid")
16. Summary
Dictionaries are one of Python’s most versatile and powerful data structures. They allow fast access, dynamic modification, and the ability to store highly structured data. Because of their efficiency, dictionaries are at the core of many Python operations, JSON parsing, APIs, configurations, and application logic.
