Skip to content

Python Dictionaries (Dictionary)

Dictionaries are a very flexible and powerful built-in data type in Python. They store data in the form of key-value pairs, providing an efficient way to look up, add, and remove entries.

Dictionary Characteristics

  • Key-Value Pairs: Each element consists of a unique "key" and a corresponding "value".
  • Unordered (Historical): In versions before Python 3.7, dictionaries were unordered. Starting with Python 3.7, dictionaries maintain the insertion order of elements.
  • Mutable: Dictionaries are mutable; you can add, modify, or delete key-value pairs at any time.
  • Unique Keys: Keys in a dictionary must be unique and must be of immutable type (such as strings, numbers, or tuples). Values can be of any type and can be repeated.

Creating Dictionaries

Dictionaries are defined using curly braces {}, containing a series of key: value pairs.

python
# Create an empty dictionary
empty_dict = {}

# Create a dictionary
person = {
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "is_student": False
}

# Can also use dict() constructor
car = dict(brand="Ford", model="Mustang", year=1964)

print(person)
print(car)

Accessing Dictionary Elements

You can access corresponding values through keys.

Using Square Brackets []

python
person = {"name": "John Doe", "age": 30}

print(person["name"]) # Output: John Doe

# If the key doesn't exist, raises KeyError
# print(person["country"]) # KeyError: 'country'

Using .get() Method

The .get() method is safer; if the key doesn't exist, it returns None (or a default value you specify) instead of raising an error.

python
person = {"name": "John Doe", "age": 30}

print(person.get("age"))        # Output: 30
print(person.get("country"))    # Output: None
print(person.get("country", "USA")) # Output: USA (provided default value)

Modifying and Adding Elements

You can add new key-value pairs or modify existing values through keys.

python
person = {"name": "John Doe", "age": 30}

# Modify existing value
person["age"] = 31
print(person) # Output: {'name': 'John Doe', 'age': 31}

# Add new key-value pair
person["city"] = "Boston"
print(person) # Output: {'name': 'John Doe', 'age': 31, 'city': 'Boston'}

Deleting Elements

  • del dict[key]: Deletes the specified key-value pair.
  • dict.pop(key): Deletes and returns the value of the specified key.
  • dict.popitem(): Deletes and returns the last inserted key-value pair (in Python 3.7+).
  • dict.clear(): Empties the dictionary.

Iterating Over Dictionaries

There are several ways to iterate over all elements in a dictionary.

python
person = {"name": "John Doe", "age": 30, "city": "New York"}

# Iterate over all keys
for key in person.keys():
    print(key)

# Iterate over all values
for value in person.values():
    print(value)

# Iterate over all key-value pairs (most common)
for key, value in person.items():
    print(f"{key}: {value}")

.keys(), .values(), and .items() return special "view objects" that provide dynamic views of dictionary entries, meaning if the dictionary changes, the views will reflect those changes accordingly.

Content is for learning and research only.