4.4 Dictionaries

4.4 Dictionaries

Understanding dictionaries (dict) for storing data in key-value pairs. We will see how to access, add, modify, and remove items, as well as how to iterate over their contents.

Dictionaries (dict) are mutable collections that store data in key-value pairs. They are optimized for fast retrieval of values when you know the key. They are one of the most important and useful data structures in Python.

Key features of dictionaries:

  • Ordered: As of Python version 3.7, dictionaries maintain the insertion order of items.
  • Mutable/Changeable: You can add, remove, or change key-value pairs.
  • Unique Keys: Each key in a dictionary must be unique.
  • Immutable Keys: Keys must be of an immutable type (e.g., string, number, tuple). Lists cannot be keys.
Dictionaries are declared with curly braces `{}`, with `key: value` pairs.

Creating and Accessing a Dictionary

Accessing a value is done by providing the corresponding key in square brackets `[]`. A safer method is `get()`, which allows you to specify a default value if the key does not exist, thus avoiding a `KeyError`.
# Creating a dictionary
person = {
    "name": "Nikos",
    "age": 30,
    "profession": "Developer",
    "languages": ["Python", "JavaScript"]
}
print(f"Dictionary: {person}")

# Accessing with a key
print(f"Name: {person['name']}")
print(f"First language: {person['languages'][0]}")

# Accessing with get() (safer)
print(f"City: {person.get('city', 'Not specified')}")

# Attempting to access a non-existent key
try:
    print(person['salary'])
except KeyError:
    print("Error: The key 'salary' does not exist.")

Modifying a Dictionary

# Modifying a dictionary
user = {"id": 101, "name": "Anna"}
print(f"Initial: {user}")

# Adding/Changing an item
user['email'] = 'anna@example.com' # Adding
user['name'] = 'Anna Papadopoulou' # Changing
print(f"Modified: {user}")

# Removing an item
removed_item = user.pop('id')
print(f"Removed id: {removed_item}, Final: {user}")

Iterating over Dictionaries

You can iterate over the keys, values, or both simultaneously using the `.keys()`, `.values()`, and `.items()` methods, respectively.
# Iterating over a dictionary
my_dict = {"a": 1, "b": 2, "c": 3}

print("\nIterating over keys:")
for key in my_dict.keys(): # or simply for key in my_dict:
    print(f"  Key: {key}")

print("\nIterating over values:")
for value in my_dict.values():
    print(f"  Value: {value}")

print("\nIterating over key-value pairs:")
for key, value in my_dict.items():
    print(f"  Key: {key}, Value: {value}")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.