Python Dictionaries and Their Usage
Work with data using key-value pairs.
What is a dictionary?
A dictionary in Python is an unordered collection of key-value pairs. Unlike lists, where you access items by position (index), dictionaries let you access values using unique keys.
Think of a dictionary like a real-life lookup table:
Creating a dictionary
person = {
"name": "Alice",
"age": 30,
"city": "Prague"
}
Accessing values by key
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
If the key doesn’t exist, Python raises a KeyError.
Using get() – safer access
print(person.get("email")) # Output: None
print(person.get("email", "N/A")) # Output: N/A
Looping through a dictionary
for key in person:
print(key, ":", person[key])
Or using items() for cleaner key-value access:
for key, value in person.items():
print(f"{key}: {value}")
Useful dictionary methods
Recommended by LinkedIn
keys() – get all keys
print(person.keys())
values() – get all values
print(person.values())
items() – list of (key, value) pairs
print(person.items())
update() – update or add items
person.update({"age": 31})
person["email"] = "alice@example.com"
pop() – remove item by key
person.pop("city")
clear() – remove all items
person.clear()
Dictionaries inside lists and nested structures
Python allows complex data structures, like lists of dictionaries:
people = [
{"name": "Tom", "age": 25},
{"name": "Eva", "age": 28}
]
for person in people:
print(person["name"])
Summary