Dictionaries in Python
A dictionary stores data as key-value pairs. Instead of looking up an item by its numeric position like a list, you look it up by a unique key, which makes dictionaries perfect for representing structured, labelled data.
Creating a Dictionary
A dictionary is written using curly braces {}, with each key and its value separated by a colon, and pairs separated by commas.
person = {"name": "Alice", "age": 30, "city": "Delhi"}
print(person)
print(type(person)) # <class 'dict'>
Accessing Values by Key
Use square brackets with the key name to read a value. If the key does not exist, Python raises a KeyError.
print(person["name"]) # Alice
print(person["age"]) # 30
print(person["email"]) # raises KeyError: 'email'
The Safer get() Method
The .get() method looks up a key without raising an error if it is missing. It returns None by default, or a fallback value that you provide.
print(person.get("name")) # Alice
print(person.get("email")) # None - no error
print(person.get("email", "not provided")) # not provided
Adding, Updating, and Removing Entries
Assigning to a new key adds an entry; assigning to an existing key updates it. The del keyword or the .pop() method removes an entry.
person["email"] = "alice@example.com" # add a new key
person["age"] = 31 # update an existing key
print(person)
del person["city"] # remove a key
print(person)
Common Dictionary Methods
| Method | Description |
|---|---|
.keys() | Returns a view of all the keys in the dictionary. |
.values() | Returns a view of all the values in the dictionary. |
.items() | Returns a view of (key, value) pairs. |
.update(other) | Merges keys and values from another dictionary into this one. |
.pop(key) | Removes a key and returns its value. |
person = {"name": "Alice", "age": 30}
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['Alice', 30])
print(person.items()) # dict_items([('name', 'Alice'), ('age', 30)])
person.update({"city": "Delhi", "age": 31})
print(person) # {'name': 'Alice', 'age': 31, 'city': 'Delhi'}
age = person.pop("age")
print(age) # 31
print(person) # {'name': 'Alice', 'city': 'Delhi'}
Looping Over a Dictionary
The most common way to loop over a dictionary is with .items(), which gives both the key and the value on each iteration.
person = {"name": "Alice", "age": 30, "city": "Delhi"}
for key, value in person.items():
print(key, "-", value)
# name - Alice
# age - 30
# city - Delhi
Dictionary Comprehensions
Just like list comprehensions, a dictionary comprehension builds a new dictionary in a single line, usually by transforming an existing one.
prices = {"pen": 10, "book": 50, "bag": 200}
doubled = {k: v * 2 for k, v in prices.items()}
print(doubled) # {'pen': 20, 'book': 100, 'bag': 400}
Checking If a Key Exists
Use the in keyword to check whether a key exists in a dictionary, before it is used, to avoid a KeyError.
person = {"name": "Alice", "age": 30}
if "name" in person:
print("Name is present")
if "email" not in person:
print("Email is not present")