Python Tutorial
Estimated reading: 3 minutes 27 views

🧾 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 / RemoveGet, update, insert, or delete dictionary entries
Dictionary: View ObjectsExplore .keys(), .values(), .items()
Loop DictionariesIterate through keys, values, or both
Copy / Nested DictionariesCreate copies and nested structures
Dictionary MethodsBuilt-in methods like get(), pop(), update(), clear()
Dictionary ExercisesPractice 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

MethodDescription
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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧾 Python Dictionaries

Or Copy Link

CONTENTS
Scroll to Top