AnyCompiler

Dictionaries

A dictionary stores key-value pairs — instead of looking something up by its position like a list, you look it up by a name you chose. It's Python's version of what other languages call a hash map or associative array.

person = {"name": "Alice", "age": 30, "city": "NYC"}
print(person)
print(person["name"])

person["age"] = 31
print(person)

person["email"] = "alice@example.com"
print(person)

print(person.keys())
print(person.values())
Output
{'name': 'Alice', 'age': 30, 'city': 'NYC'}
Alice
{'name': 'Alice', 'age': 31, 'city': 'NYC'}
{'name': 'Alice', 'age': 31, 'city': 'NYC', 'email': 'alice@example.com'}
dict_keys(['name', 'age', 'city', 'email'])
dict_values(['Alice', 31, 'NYC', 'alice@example.com'])
  • person["name"] reads the value stored under the key "name"
  • Assigning to an existing key updates its value; assigning to a new key adds it — the same syntax does both
  • .keys() and .values() give you every key or every value, in insertion order

Next: sets — a collection that automatically removes duplicates and supports real mathematical set operations.

Practice exercise

Create person = {"name": "Alice", "age": 30}. Update age to 31, then print person["age"].