Dictionaries in Python
Key-value storage, safe lookups with get(), looping over items, and why dictionaries beat parallel lists.
5 minute read · Free · Taught properly in our Python Training in Amritsar
A dictionary stores pairs: a key, and the value that key points at.
student = {
"name": "Simran",
"course": "Python",
"months": 4,
}
student["name"] # 'Simran'
student["months"] = 5 # change it
student["city"] = "Amritsar" # add a new pair
Keys are usually strings, but any immutable value works — numbers and tuples are fine, lists are not.
Looking things up without crashing
student["phone"] # KeyError — the key is not there
student.get("phone") # None, no crash
student.get("phone", "n/a") # 'n/a'
Use .get() whenever the key might be missing — reading an API response, a config file, or anything a user typed. Use square brackets when a missing key means something is genuinely broken and you want to hear about it immediately.
To check first:
if "phone" in student:
print(student["phone"])
Looping
for key in student:
print(key) # keys only
for key, value in student.items():
print(key, "=", value) # both
.items() is what you want nine times out of ten. There is also .keys() and .values().
Why this beats parallel lists
Students often start with two lists that have to stay lined up:
names = ["Simran", "Ravi"]
marks = [88, 72]
Now every sort, insert and delete has to happen twice, in step, or the data silently goes wrong. A dictionary keeps the pairing:
marks = {"Simran": 88, "Ravi": 72}
marks["Ravi"] # 72
Nesting
Real data is usually a list of dictionaries:
batch = [
{"name": "Simran", "marks": 88},
{"name": "Ravi", "marks": 72},
]
for s in batch:
print(s["name"], s["marks"])
top = max(batch, key=lambda s: s["marks"])
That shape — a list of dictionaries — is what you get back from almost every JSON API, so it is worth being comfortable with it before you touch one.
Stuck on this in your own code?
That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some Python, ask the mentor why yours is not working, and decide afterwards.