Up until now, we’ve used Lists to store data. Lists are great when order matters, like a “Top 10” list. But they are terrible for describing things.
Imagine a list representing a person: ["Daniel", 28, "Poland"].
- To get the name, you have to remember it’s at index
0. - To get the age, you have to remember it’s at index
1. - If the list grows, you’ll eventually lose track of what the numbers mean.
A Dictionary solves this by using Labels (Keys) instead of numbers. Instead of “item 0,” you just ask for “name.”
What is JSON?
Think of JSON (JavaScript Object Notation) as the “Universal Language of the Internet.” When a weather app asks a server for the temperature, or when you log into a website, the data is sent as a text file called JSON.
JSON looks and acts almost exactly like a Python Dictionary.
Keys and Values
Let’s get back to the dictionary: it’s a bunch of key-value pairs that we write inside curly brackets {}.
- The Key: The label (usually a string). Must be unique.
- The Value: The data stored under that label.
user = {
"name": "Bob",
"age": 30,
"is_active": True
# Accessing a value
print(user["name"]) # Output: Bob
Dictionary keys are case-sensitive. "NAME", "Name" and "name" are three different drawers in Python’s eyes.
Modifying Dictionaries
Dictionaries are mutable, meaning you can change them on the fly.
Add / Update
You can add or change data just by “assigning” it to a key.
user = {
"name": "Bob",
"age": 30
}
# Update an existing key
user["age"] = 31
# Add a brand new label
user["job"] = "Developer"
The .update() method is useful when you want to change many things at once.
user.update({"age": 32, "city": "Warsaw"})
# You can also use `.update()` without the curly braces
# by using keyword arguments.
user.update(age=32, city="Warsaw")
Deletion
You can remove data using del or .pop().
Use .pop() if you want to use the value one last time before it’s deleted.
user = {"name": "Bob", "email": "bob@example.com", "status": "active"}
# Just deletes status
del user["status"]
# Removes email, but saves it to a variable first
old_email = user.pop("email")
print(user) # {'name': 'Bob'}
print(old_email) # bob@example.com
.get() method
If you ask for a key that doesn’t exist (like user["salary"]), Python will crash with a KeyError. Using .get() is the way to handle this because it returns None (or a default message) instead of crashing.
user = {"name": "Bob"}
# print(user["salary"]) # CRASH!
print(user.get("salary")) # Output: None
print(user.get("salary", "Not specified")) # Output: Not specified
Useful Tools
len(user): How many keys are in the dictionary?"name" in user: Does this key exist? (Returns True/False)
user = {"name": "Daniel", "age": 28}
print(len(user)) # 2, since we have 2 keys (name, age)
print("name" in user) # True
print("salary" in user) # False
Iterating (Looping)
You can choose to loop through just the keys, just the values, or both.
inventory = {"Apples": 10, "Bananas": 5}
# .items(): Get both (Key and Value)
for item, count in inventory.items():
print(f"{item}: {count}")
# .keys(): Get just the Keys
for item in inventory.keys():
print(item)
# .values(): Get just the Values
for count in inventory.values():
print(count)
Nested Data (The JSON Look)
In the real world, data is often “nested”, meaning a dictionary can hold a list, or even another dictionary. This is exactly how complex JSON data from the web looks.
user_account = {
"username": "dan_codes",
"friends": ["Alice", "Bob"], # A List inside a Dict
"profile": { # A Dict inside a Dict
"city": "Krakow",
"verified": True
}
}
# To get the city:
print(user_account["profile"]["city"]) # Output: Krakow
Most of the time, you will have more than one account. In this case, we put multiple dictionaries inside a single list.
users = [
{
"id": 1,
"username": "dan_codes",
"profile": {"city": "Krakow"}
},
{
"id": 2,
"username": "bob_builds",
"profile": {"city": "London"}
}
]
# Accessing the second user's city:
print(users[1]["profile"]["city"]) # Output: London