SyntaxStudy
Sign Up
Python Intermediate 9 min read

Dictionaries

Python Dictionaries

Dictionaries store key-value pairs with O(1) average lookup.

Creating

person = {"name": "Alice", "age": 30}
person = dict(name="Alice", age=30)

Accessing

print(person["name"])
print(person.get("email", "N/A"))

Modifying

person["email"] = "alice@example.com"
person.update({"age": 31, "city": "NY"})

Iterating

for key in person:
    print(key, person[key])

for key, value in person.items():
    print(f"{key}: {value}")

Methods

print(person.keys())
print(person.values())
del person["age"]
person.pop("city", None)
Pro Tip

Dict keys must be immutable (strings, numbers, tuples). Lists cannot be keys.