Python Dictionaries
Python dictionaries store data as key-value pairs, so you can look up a value by its key instead of by position. Dictionaries are written with curly braces, are mutable, and keep the order in which keys were inserted (since Python 3.7). Keys must be unique.
Create a Dictionary and Access Values
customer = {
"name": "Ahmed Ali",
"city": "Dubai",
"orders": 4,
}
print(customer["name"])
print(customer.get("city"))
print(customer.get("phone"))
print(customer.get("phone", "not provided"))Ahmed Ali Dubai None not provided
Square brackets raise a KeyError when a key does not exist. get() returns None, or a default you choose, which is safer for optional data.
Add, Change and Remove Keys
stock = {"rice": 120, "tea": 300}
stock["honey"] = 0 # add a new key
stock["tea"] = 280 # change a value
stock.update({"rice": 100, "oil": 45})
removed = stock.pop("honey")
print(removed)
print(stock)0
{'rice': 100, 'tea': 280, 'oil': 45}Check if a Key Exists
The in operator checks keys, not values. To search values, use in with .values().
capitals = {"Pakistan": "Islamabad", "Spain": "Madrid"}
print("Spain" in capitals)
print("Madrid" in capitals)
print("Madrid" in capitals.values())True False True
Loop Through a Dictionary
Looping over a dictionary gives its keys. items() gives key and value together, which is what you want most of the time.
prices = {"coffee": 22.0, "almonds": 15.0, "chocolate": 4.25}
for item, price in prices.items():
print(f"{item}: {price}")
print(list(prices.keys()))
print(max(prices, key=prices.get))coffee: 22.0 almonds: 15.0 chocolate: 4.25 ['coffee', 'almonds', 'chocolate'] coffee
Counting with a Dictionary
A classic use of dictionaries is counting things. get() with a default of 0 handles keys seen for the first time. The Counter class from collections does the same job in one line.
from collections import Counter
text = "banana"
counts = {}
for ch in text:
counts[ch] = counts.get(ch, 0) + 1
print(counts)
print(Counter(text).most_common(1)){'b': 1, 'a': 3, 'n': 2}
[('a', 3)]Nested Dictionaries
Values can be any type, including lists and other dictionaries. This is how JSON data from web APIs looks once loaded into Python.
users = {
"u1": {"name": "Emma", "skills": ["python", "sql"]},
"u2": {"name": "Liam", "skills": ["java"]},
}
print(users["u1"]["name"])
print(users["u1"]["skills"][1])
for uid, info in users.items():
print(uid, info["name"], len(info["skills"]))Emma sql u1 Emma 2 u2 Liam 1
Useful Dictionary Methods
- keys(), values() and items() return views of the dictionary
- get(key, default) reads safely; setdefault(key, default) reads or inserts
- pop(key) removes a key and returns its value; clear() empties the dictionary
- copy() makes a shallow copy; d1 | d2 merges two dictionaries (Python 3.9+)
Frequently asked questions
How do I check if a key exists in a Python dictionary?
Use the in operator: if "name" in my_dict:. It checks keys only, and it is very fast.
What is the difference between dict[key] and dict.get(key)?
dict[key] raises a KeyError if the key is missing. dict.get(key) returns None or a default value you pass as the second argument.
Are Python dictionaries ordered?
Yes. Since Python 3.7, dictionaries keep keys in the order they were inserted.
How do I merge two dictionaries in Python?
In Python 3.9 and newer use merged = d1 | d2. In older versions use {**d1, **d2} or d1.update(d2).