Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 12

Dictionaries: key and value

FreeLesson 14 of 78

A dictionary stores pairs: a key you look up, and the value it points to. It is the most useful structure in data engineering.

CREATE, READ, CHANGE, ADD, REMOVEPYTHON 3.12
customer = {
    "id": 4,
    "name": "Meera",
    "city": "Bengaluru",
}
print(customer["name"])                 # look up by key
customer["city"] = "Pune"               # change a value
customer["tier"] = "gold"               # add a new key
del customer["id"]                      # remove a key
print(customer)
print(customer.get("phone"), customer.get("phone", "not given"))
print("tier" in customer, len(customer))

Output

Meera
{'name': 'Meera', 'city': 'Pune', 'tier': 'gold'}
None not given
True 3
LOOPING OVER A DICTIONARYPYTHON 3.12
prices = {"Mouse": 799, "Hub": 1499, "Pens": 149}

for product in prices:                  # loops over keys
    print(product, end=" ")
print()
for product, price in prices.items():   # key and value together
    print(f"{product:<6} {price:>5}")
print(list(prices.keys()), list(prices.values()))

Output

Mouse Hub Pens
Mouse    799
Hub     1499
Pens     149
['Mouse', 'Hub', 'Pens'] [799, 1499, 149]
THE TWO JOBS DICTS DO ALL DAY: COUNT AND GROUPPYTHON 3.12
statuses = ["delivered", "cancelled", "delivered",
            "returned", "delivered"]

counts = {}
for s in statuses:
    if s in counts:
        counts[s] += 1
    else:
        counts[s] = 1
print(counts)

orders = [                         # a list of dicts: the
    {"id": 101, "city": "Pune", "amount": 1198},   # shape of
    {"id": 102, "city": "Delhi", "amount": 796},   # most real
    {"id": 103, "city": "Pune", "amount": 1499},   # data
]
by_city = {}
for o in orders:
    by_city[o["city"]] = by_city.get(o["city"], 0) + o["amount"]
print(by_city)

Output

{'delivered': 3, 'cancelled': 1, 'returned': 1}
{'Pune': 2697, 'Delhi': 796}

Try it yourself before moving on

  1. Make a dict of product to price and print the cheapest product.
  2. Count each letter in "mississippi" with a dict.
  3. Group the words ["apple", "avocado", "banana", "blueberry"] by first letter.

Watch the free lesson

The same topic in the Free Lessons library, free with a sign-in.