Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
DATA STRUCTURES Module 3 - Data Structures Python Python Basics Python Programming: From Zero to Real-World Applications

Dictionaries - Key-Value Pairs in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to create and access dictionaries
  • Adding, updating, and deleting keys
  • Iterating over dictionaries
Terminalpython
# Creating dictionaries
person = {
    "name": "Anita",
    "age": 28,
    "city": "Mumbai"
}

# Accessing (by key)
print(person["name"])    # Anita
print(person.get("age"))  # 28

# .get() returns None (or default) if key not found
print(person.get("email"))              # None
print(person.get("email", "N/A"))       # N/A

Adding, Updating, and Deleting

Terminalpython
person = {"name": "Anita", "age": 28}

# Add new key
person["email"] = "anita@example.com"

# Update existing
person["age"] = 29

# Delete
del person["email"]
popped = person.pop("age")   # Remove and return value

print(person)   # {'name': 'Anita'}
print(popped)   # 29

Iterating Over Dictionaries

Terminalpython
person = {"name": "Anita", "age": 28, "city": "Mumbai"}

# Keys only
for key in person.keys():
    print(key)

# Values only
for value in person.values():
    print(value)

# Both (most common)
for key, value in person.items():
    print(f"{key}: {value}")
KeyError
Accessing a non-existent key with [] raises KeyError. Use .get() to avoid errors: person.get("missing", "default").

Practical Exercise

Create a dict: {"name": "Anita", "age": 28, "city": "Mumbai"}
Access: print(person["name"])
Add: person["email"] = "anita@example.com"
Loop with .items(): for k, v in person.items()
Use .get() for a missing key

Key Takeaways

  • Dictionaries store key-value pairs.
  • Access with dict[key] or safer dict.get(key, default).
  • Add/update: dict[key] = value. Delete: del dict[key].
  • Iterate: .keys(), .values(), .items().
  • Keys must be immutable (str, int, tuple - not list).
Previously: Lesson 18 covered tuples.
Today: You learned: Dictionaries - key-value pairs, the power tool of Python.
Next: Lesson 20 covers dict methods.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments