π§Ύ Python Dictionaries β Access, Update, Loop & Nested Dictionary Examples
π§² Introduction β Why Use Dictionaries in Python?
A dictionary in Python is an unordered collection of data stored in key-value pairs. Unlike lists that use numeric indexes, dictionaries use keys, which can be strings, numbers, or tuples. Theyβre ideal for representing structured data like JSON, configuration files, or database records.
π― In this guide, you’ll learn:
- How to create and manage dictionaries
- How to view, loop, and manipulate dictionary data
- Common methods for working with dictionaries
- Real-world usage through practice exercises
π Topics Covered
π§© Topic | π Description |
---|---|
Dictionary: Access / Change / Add / Remove | Get, update, insert, or delete dictionary entries |
Dictionary: View Objects | Explore .keys() , .values() , .items() |
Loop Dictionaries | Iterate through keys, values, or both |
Copy / Nested Dictionaries | Create copies and nested structures |
Dictionary Methods | Built-in methods like get() , pop() , update() , clear() |
Dictionary Exercises | Practice problems to reinforce learning |
π§ Python Dictionary: Access / Change / Add / Remove Items
πΉ Creating a Dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
πΉ Accessing Items
print(person["name"]) # Alice
print(person.get("age")) # 30
πΉ Changing Items
person["city"] = "Boston"
πΉ Adding Items
person["email"] = "alice@example.com"
πΉ Removing Items
person.pop("age")
del person["city"]
π Python Dictionary: View Objects
Dictionaries allow access to three types of view objects:
print(person.keys()) # dict_keys(['name', 'email'])
print(person.values()) # dict_values(['Alice', 'alice@example.com'])
print(person.items()) # dict_items([('name', 'Alice'), ('email', 'alice@example.com')])
β These return dynamic views that update when the dictionary changes.
π Python Dictionary: Loop Dictionaries
πΉ Loop through keys
for key in person:
print(key)
πΉ Loop through values
for value in person.values():
print(value)
πΉ Loop through key-value pairs
for key, value in person.items():
print(f"{key} = {value}")
π§³ Python Copy / Nested Dictionaries
πΉ Copying a Dictionary
copy_person = person.copy()
πΉ Nested Dictionaries
family = {
"child1": {"name": "Anna", "age": 5},
"child2": {"name": "Tom", "age": 8}
}
print(family["child1"]["name"]) # Anna
π οΈ Python Dictionary Methods
Method | Description |
---|---|
get() | Safely get a value |
update() | Merge another dict or key-value pairs |
pop() | Remove a key and return its value |
popitem() | Remove the last inserted item |
setdefault() | Get value or set default |
clear() | Remove all items |
copy() | Return a shallow copy |
π§ͺ Python Dictionary Exercises
β 1. Access and print value by key
student = {"name": "Bob", "grade": "A"}
print(student["grade"]) # A
β 2. Update and add new item
student["grade"] = "B"
student["passed"] = True
print(student)
β 3. Loop through dictionary
for k, v in student.items():
print(f"{k} => {v}")
β 4. Create a nested dictionary
contacts = {
"john": {"phone": "123", "email": "john@example.com"},
"jane": {"phone": "456", "email": "jane@example.com"}
}
print(contacts["jane"]["email"]) # jane@example.com
π Summary β Recap & Next Steps
Python dictionaries provide a flexible and powerful way to work with structured data. With efficient access and built-in methods, dictionaries are widely used in everything from data processing to API responses.
π Key Takeaways:
- Dictionaries store data in key-value pairs.
- Use
.get()
,.pop()
, and.update()
for safe data manipulation. - Nested dictionaries help structure complex information.
- Loops help you efficiently traverse dictionary items.
βοΈ Real-World Relevance:
Used heavily in configuration files, databases, APIs (like JSON), and applications where data must be associated by name or ID.
β FAQ β Python Dictionaries
β What is a Python dictionary?
β
A dictionary is a collection of key-value pairs. Keys must be unique and immutable (e.g., strings, numbers, tuples).
β Can you have duplicate keys in a dictionary?
β
No. Later assignments overwrite earlier ones.
β How do you safely get a value without a KeyError?
β
Use .get()
instead of square brackets:
value = mydict.get("key", "default")
β Can you nest dictionaries inside each other?
β
Yes. You can have dictionaries within dictionaries to model complex structures.
β What is the difference between .pop()
and del
?
β
.pop()
returns the value and is safer. del
just removes the key.
Share Now :