Dictionaries
Dictionaries store data as key/value pairs.
Syntax
person = {'name': 'Ada', 'age': 36}A dictionary stores data as key/value pairs. Write it with curly braces and colons. Look up a value by its key.
Working with dictionaries
- Add or change with
d[key] = value. - Read safely with
d.get(key), which returnsNoneif the key is missing. - Loop with
d.items(),d.keys(), andd.values().
Example
person = {'name': 'Ada', 'age': 36}
print(person['name'])
print(person.get('city'))
person['city'] = 'London'
for key, value in person.items():
print(key, '=', value)
# Output:
# Ada
# None
# name = Ada
# age = 36
# city = LondonWhen to use it
- A user profile stores keys like 'name', 'email', and 'age' mapped to their respective values.
- A word-frequency counter updates a dictionary key's count each time a word is encountered.
- A cache stores API responses keyed by request URL to avoid redundant network calls.
More examples
Create and access a dictionary
Creates a dict and uses bracket access for known keys and .get() with a default for optional ones.
user = {'name': 'Alice', 'age': 30, 'city': 'Oslo'}
print(user['name']) # Alice
print(user.get('email', 'N/A')) # N/A (key missing)Add, update, and delete keys
Shows how to add a new key, update an existing one, and remove a key with del.
config = {'debug': False, 'port': 8080}
config['host'] = 'localhost' # add
config['port'] = 3000 # update
del config['debug'] # delete
print(config)
# {'port': 3000, 'host': 'localhost'}Iterate over a dictionary
Iterates over key-value pairs using .items() and prints each with an f-string.
scores = {'Alice': 92, 'Bob': 85, 'Carol': 98}
for name, score in scores.items():
print(f'{name}: {score}')
# Output:
# Alice: 92
# Bob: 85
# Carol: 98
Discussion