Code / Python for Beginners / Unit 4: Lists and dictionaries

Dictionaries डिक्शनरी

Lesson 11 of 14 · about 16 minutes · Look things up by name: keys, .get() and .items().

⚡ 0 XP

Step 1 of 2

A price list

name"Asha"class9city"Surat"

A dictionary (dict) stores pairs of key: value, like a price list at a kirana shop:

prices = {"atta": 55, "dal": 120}

  • prices["dal"] gives 120
  • prices["ghee"] = 650 adds a new pair (or changes an old one)
  • prices["salt"] crashes with a KeyError if salt is missing
  • prices.get("salt", 0) is the safe way: it gives 0 when salt is missing
  • "dal" in prices checks whether a key exists
Example
prices = {"atta": 55, "dal": 120}
prices["ghee"] = 650
print(prices)
print(prices["dal"])
print(prices.get("salt", 0))

🎯 Challenge: Kirana price checker +20 XP

First add ghee to prices at ₹650. Then read an item and look it up with .get(item, 0). If the price is more than 0, print dal costs ₹120; otherwise print Sorry, no salt today (with the real item name). (Prices are sample data.)

Try twice to unlock the solution (0/2)

main.pyCtrl ⏎
Output

What your program prints appears here.

Checklist

Press Run to check your code.

  • ghee is in the price list at ₹650
  • dal and ghee show their prices
  • A missing item does not crash
  • Uses .get()
Lesson notes (text version)

1. A price list

A dictionary (dict) stores pairs of key: value, like a price list at a kirana shop:

prices = {"atta": 55, "dal": 120}

  • prices["dal"] gives 120
  • prices["ghee"] = 650 adds a new pair (or changes an old one)
  • prices["salt"] crashes with a KeyError if salt is missing
  • prices.get("salt", 0) is the safe way: it gives 0 when salt is missing
  • "dal" in prices checks whether a key exists
                prices = {"atta": 55, "dal": 120}
prices["ghee"] = 650
print(prices)
print(prices["dal"])
print(prices.get("salt", 0))
              

Challenge: Kirana price checker

First add ghee to prices at ₹650. Then read an item and look it up with .get(item, 0). If the price is more than 0, print dal costs ₹120; otherwise print Sorry, no salt today (with the real item name). (Prices are sample data.)

2. Looping over a dict

for key, value in d.items(): walks through every pair of a dictionary, giving you both the key and the value each time.

Two dicts with the same keys work great together: one says how many boxes you bought, the other says the price of each. Look up the price with the key from the first dict.

                marks = {"Maths": 92, "Hindi": 85}
for subject, m in marks.items():
    print(subject, "->", m)
              

Challenge: Diwali sweets bill

Loop over cart.items(). For each sweet, work out boxes × price, add it to total, and print a line like laddoo x3 = ₹900. After the loop print Total: ₹2150. (Prices are sample data.)

Search by task, format or tool name.