Looping Through Dictionaries and Counting

Looping over a dictionary

prices = {"tea": 20, "coffee": 35, "samosa": 15}

for item in prices:
    print(item)

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

Output

tea
coffee
samosa
tea costs 20
coffee costs 35
samosa costs 15
CodeGives you
for key in deach key
d.values()each value
d.items()each (key, value) pair
prices = {"tea": 20, "coffee": 35, "samosa": 15}
print("Total for one of each:", sum(prices.values()))

Output

Total for one of each: 70

Counting with a dictionary

One of the most useful patterns in Python: count how many times each thing appears.

words = "the cat and the dog and the bird".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

Output

{'the': 3, 'cat': 1, 'and': 2, 'dog': 1, 'bird': 1}

counts.get(word, 0) gives the current count, or 0 the first time we see a word. Then we add 1.

Lists inside dictionaries

Values can be anything – even lists or other dictionaries:

classes = {
    "Python": ["Asha", "Ravi"],
    "Linux": ["Meena"],
}
classes["Linux"].append("Kabir")
for course, students in classes.items():
    print(course, "->", ", ".join(students))

Output

Python -> Asha, Ravi
Linux -> Meena, Kabir

Tip: Choosing the right collection: list for an ordered group, tuple for fixed values, set for unique values, dict to look things up by name.

HOME LEARN COMMUNITY DASHBOARD