Python Dictionaries
Dictionaries (dict) in Python are unordered, mutable collections of key-value pairs. They are
optimized for fast data lookup and are widely used in real-world applications like JSON data handling,
database operations, and more.
What is a Dictionary?:
- Stores data in key: value pairs.
- Keys must be unique & immutable (e.g., strings, numbers, tuples).
- Values can be any data type (lists, sets, other dictionaries, etc.).
- Defined using curly braces {} or the dict() constructor.
Example:
student = {"name": "Alice", "age": 21, "courses": ["Math", "CS"]}
print(student)
# Output: {'name': 'Alice', 'age': 21, 'courses': ['Math', 'CS']}
1. Creating Dictionaries
# Using curly braces
person = {"name": "John", "age": 30, "city": "New York"}
# Using dict() constructor
person2 = dict(name="Jane", age=25, city="London")
2. Accessing Values
print(person["name"]) # Output: John
print(person.get("age")) # Output: 30
print(person.get("salary", "Not found")) # Default value
3. Updating Values
person["age"] = 35
person["salary"] = 50000 # Adds new key
4. Deleting Items
del person["city"] # Deletes 'city'
person.pop("salary") # Removes 'salary'
person.clear() # Removes all items
5. Looping Through a Dictionary
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, ":", value)
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['John', 35])
print(person.items()) # dict_items([('name', 'John'), ('age', 35)])
6. Dictionary Methods :
| Method |
Description |
get(key) |
Returns value for key or None |
keys( ) |
Returns all keys |
values( ) |
Returns all values |
items( ) |
Returns key-value pairs |
update(dict) |
Updates one dict with another |
pop(key) |
Removes key and returns value |
clear( ) |
Empties the dictionary |
copy( ) |
Shallow copy of the dictionary |
setdefault(k,v) |
Returns key value or sets default |
7. Nested Dictionaries
students = {
"101": {"name": "Alice", "marks": 85},
"102": {"name": "Bob", "marks": 90}
}
print(students["101"]["name"]) # Output: Alice
8. Dictionary Comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
9. Merging Dictionaries
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
c = {**a, **b} # Merges a and b, b's values override
print(c) # Output: {'x': 1, 'y': 3, 'z': 4}
10. Use Case: Counting Elements
text = "banana"
count = {}
for char in text:
count[char] = count.get(char, 0) + 1
print(count)
# Output: {'b': 1, 'a': 3, 'n': 2}
11. Immutable Keys Only
d = {("a", "b"): 1} # Tuple as key
12. Dictionary vs List
| Feature |
Dictionary |
List |
Access |
Key-based (dict[key]) |
Index-based (list[index]) |
Uniqueness |
Keys must be unique |
Duplicates allowed |
Lookup speed |
Fast |
Slower (in large data) |
Common Python Dictionary Questions
Here are some of the most common and important dictionary questions in Python, suitable for interviews, exams, and practice:
A dictionary is an unordered collection of key-value pairs. Keys must be unique and immutable.
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"])
print(my_dict.get("age"))
d["missing"] → raises KeyError
d.get("missing") → returns None (or default value if provided)
my_dict["city"] = "Delhi"
my_dict["age"] = 30
del my_dict["city"]
my_dict.pop("age")
for k, v in my_dict.items():
print(k, v)
Used to safely access keys with a default return value.
my_dict.get("salary", "Not Found")
No, keys must be immutable (e.g., int, str, tuple).
d1 = {"a": 1}
d2 = {"b": 2}
d3 = {**d1, **d2}
new_dict = my_dict.copy()
squares = {x: x*x for x in range(5)}
text = "banana"
count = {}
for char in text:
count[char] = count.get(char, 0) + 1
keys() → returns keys
values() → returns values
items() → returns key-value pairs
No, duplicate keys overwrite the previous value.
d = {"a": 1, "a": 2} # Final dict: {"a": 2}