Looking up and updating
ages = {"Riya": 19, "Arjun": 21}
print(ages["Riya"])
ages["Meera"] = 20
ages["Riya"] += 1
print(ages)Write Python. Understand every error.
Python basics · topic 13 of 25
A dictionary stores pairs of keys and values, like a real dictionary stores words and meanings. You look up a value by its key, not by position.
prices = {"tea": 10, "samosa": 15}
print(prices["tea"])You can add or change an entry with d[key] = value. Looking up a missing key causes a KeyError, so use d.get(key, default) when the key might not exist.
Loops over dictionaries are common. d.keys() gives the keys, d.values() the values, and d.items() both together.
for item, price in prices.items(): print(item, price)
A dictionary is also the standard tool for counting: start each count at 0 with get, then add 1.
d[key] = value adds or changes an entry.d.get(key, default) is a safe lookup that does not fail when the key is missing.d.items() gives keys and values together, and counting with get(key, 0) + 1 is a standard pattern.d[0] to mean the first entry. Dictionaries use keys, not positions. Read the KeyError guide.
ages = {"Riya": 19, "Arjun": 21}
print(ages["Riya"])
ages["Meera"] = 20
ages["Riya"] += 1
print(ages)stock = {"pen": 12, "pencil": 30}
print(stock.get("pen", 0))
print(stock.get("eraser", 0))marks = {"maths": 88, "physics": 76, "english": 91}
for subject, m in marks.items():
print(subject, m)
print("total", sum(marks.values()))word = "banana" counts = {} for ch in word: counts[ch] = counts.get(ch, 0) + 1 print(counts)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
d = {"a": 1, "b": 2}
d["c"] = 3
print(len(d))Assigning to a new key adds it to the dictionary.
d = {"x": 10}
print(d.get("y", 0)).get() returns the default value 0 because "y" is not a key.
d["z"] do if "z" is not a key in d?Square brackets need the key to exist. Use .get() when it might be missing.
marks = {"Riya": 90, "Arjun": 75}
for name, m in marks.items():
print(name, m).items() gives key and value pairs, which the loop unpacks.
counts = {}
for ch in "aab":
counts[ch] = counts.get(ch, 0) + 1
print(counts)This is the standard counting pattern with .get(key, 0) + 1.