Ravindra BagaleCourses & study guides मराठी Track your progress

Python Lists, Tuples, Dictionaries and Sets Explained with Examples

P4.3 Python Dictionaries: Keys and Values Explained

Why. Sometimes you look things up by name, not position: the price of "milk", the balance of account "AC-77". A dictionary is built for this.

What. A dictionary (dict) stores key: value pairs inside {}. Keys are unique labels. Values can be anything.

  • d["key"] — read a value
  • d["key"] = v — add or change
  • d.get("key", default) — read safely
  • d.keys(), d.values(), d.items() — all keys, values, pairs

How.

Use a dictionary

  1. Create it with {key: value}.
  2. Read with d[key].
  3. Update with d[key] = new.
  4. Use get when a key may be missing.

Worked example A — A price list.

Step 1 — What we do. A grocery shop in Kolhapur keeps prices by item name.

Step 2 — Type and run this code.

prices = {"milk": 56, "bread": 40, "eggs": 84}
print(prices["milk"])

Step 3 — Output you should see.

56

Step 4 — What it means. We read by name, not by position. The key "milk" gives 56 (₹56).

Worked example B — Add, change and read safely.

Step 1 — What we do. Bread price changes, butter is added, and we look for an item that does not exist.

Step 2 — Type and run this code.

prices = {"milk": 56, "bread": 40, "eggs": 84}
prices["bread"] = 45
prices["butter"] = 60
print(prices)
print(prices.get("jam", 0))

Step 3 — Output you should see.

{'milk': 56, 'bread': 45, 'eggs': 84, 'butter': 60}
0

Step 4 — What it means. Same key = update, new key = add. get("jam", 0) returns 0 instead of an error.

Worked example C — A customer record.

Step 1 — What we do. A bank in Zurich stores one customer as a dictionary.

Step 2 — Type and run this code.

customer = {"id": "AC-77", "name": "Lukas", "balance": 5400.0, "currency": "CHF"}
print(customer["name"], customer["balance"], customer["currency"])
for key, value in customer.items():
    print(key, "->", value)

Step 3 — Output you should see.

Lukas 5400.0 CHF
id -> AC-77
name -> Lukas
balance -> 5400.0
currency -> CHF

Step 4 — What it means. Each key is like a column name and each value is that column for one row. .items() gives each pair (we learn loops fully in the loops chapter).

Python next to other languages — look up a value by key. You do not need to learn these other languages. This only shows why Python is easier to read.

Language Code
Python prices["milk"]
Java prices.get("milk") (with a HashMap)
JavaScript prices["milk"] (an object)
Go prices["milk"] (a map)

Ravindra Bagale's Tip

Think "dictionary = one row". Keys are column names. This makes pandas feel natural later.