Back to Blog

Learn Python Dictionaries - get(), items(), pop(), Comprehensions (Tutorial #10)

Sandy LaneSandy Lane

Video: Learn Python Dictionaries - get(), items(), pop(), Comprehensions (Tutorial #10) by Taught by Celeste AI - AI Coding Coach

Watch full page →

Learn Python Dictionaries - get(), items(), pop(), Comprehensions (Tutorial #10)

Dictionaries in Python are powerful data structures that store key-value pairs. This tutorial covers how to create, access, modify, and iterate over dictionaries, as well as useful methods like get(), pop(), and dictionary comprehensions to write concise code.

Code

# Creating a dictionary with curly braces
person = {"name": "Alice", "age": 25}

# Accessing values using brackets and get()
print(person["name"])            # Output: Alice
print(person.get("email", "N/A"))  # Output: N/A (default if key not found)

# Modifying dictionary: adding, updating, deleting
person["city"] = "New York"     # Add new key-value pair
person.update({"age": 26})      # Update existing key
del person["city"]              # Delete a key-value pair

# Dictionary methods: keys(), values(), items()
scores = {"Alice": 90, "Bob": 85, "Charlie": 92}
for k, v in scores.items():
  print(f"{k} scored {v}")

# Using update() and pop()
new_scores = {"Bob": 88, "Diana": 95}
scores.update(new_scores)       # Merge dictionaries
removed_score = scores.pop("Charlie", 0)  # Remove key, default 0 if missing

# Dictionary comprehension: create squares dict
squares = {x: x ** 2 for x in range(6)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Mini project: Contact Book with nested dictionaries
contacts = {}
name = "Eve"
phone = "123-456-7890"
email = "eve@example.com"
contacts[name] = {"phone": phone, "email": email}

for name, info in contacts.items():
  print(f"{name}: {info['phone']}")

Key Points

  • Dictionaries store data as key-value pairs and are created using curly braces.
  • The get() method safely accesses values with a default if the key is missing.
  • Use update() to merge dictionaries and pop() to remove keys with optional defaults.
  • Iterate over dictionaries with items() to access keys and values simultaneously.
  • Dictionary comprehensions provide a concise way to generate dictionaries from iterables.