indusai.co

Dictionaries

A dictionary stores pairs of keys and values. You look values up by key instead of by position, which makes dictionaries the natural way to represent records, lookups and counts.

Creating a dictionary

python
student = {
    "name": "Nikhil",
    "age": 21,
    "course": "Data Science",
}
print(student)
print(len(student))

Keys must be immutable (strings, numbers, tuples) and unique. Values can be anything. Since Python 3.7 dictionaries keep the order in which keys were inserted.

Reading values

python
student = {"name": "Nikhil", "age": 21}
print(student["name"])
print(student.get("age"))
print(student.get("email"))              # None instead of an error
print(student.get("email", "not set"))   # custom default

student["email"] would raise KeyError. Use get() when the key might be missing.

Adding and changing

python
student = {"name": "Nikhil"}
student["age"] = 21          # add a new key
student["name"] = "Nikhil R" # change an existing one
student.update({"city": "Kota", "age": 22})
print(student)

Removing

python
student = {"name": "Nikhil", "age": 21, "city": "Kota"}
age = student.pop("age")
print(age, student)

del student["city"]
print(student)

student.clear()
print(student)

Checking for a key

python
student = {"name": "Nikhil"}
print("name" in student)
print("age" in student)

Looping

python
prices = {"tea": 10, "coffee": 25, "juice": 40}

for key in prices:
    print(key)

for value in prices.values():
    print(value)

for item, price in prices.items():
    print(f"{item}: Rs {price}")

Nested dictionaries

python
classroom = {
    "s1": {"name": "Anu", "marks": 91},
    "s2": {"name": "Dev", "marks": 78},
}
print(classroom["s2"]["name"])

for sid, info in classroom.items():
    print(sid, info["name"], info["marks"])

Counting with a dictionary

A very common pattern: use get with a default of 0.

python
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts)

collections.Counter does the same in one line:

python
from collections import Counter
print(Counter("the cat and the hat and the bat".split()))

Dictionary comprehensions

python
squares = {n: n ** 2 for n in range(5)}
print(squares)

names = ["ana", "bo"]
upper = {n: n.upper() for n in names}
print(upper)

Other methods

python
d = {"a": 1, "b": 2}
print(list(d.keys()))
print(list(d.values()))
print(d.setdefault("c", 3))   # returns existing value or inserts default
print(d)
merged = d | {"d": 4}         # merge, Python 3.9+
print(merged)

Practice

  1. Build a dictionary mapping three country names to their capitals. Print each pair as "The capital of X is Y".
  2. Given a list of marks, build a dictionary that counts how many are above 80 and how many are not.
  3. Invert {"a": 1, "b": 2} to {1: "a", 2: "b"} with a comprehension.