← Python for Beginners
0 of 27 lessons done0%

Collections · Lesson 20 of 27

Dictionaries

A dictionary stores key: value pairs. You look things up by key instead of by position.

student = {"name": "Riya", "age": 21}
print(student["name"])       # Riya
student["city"] = "Noida"    # add a new pair
student["age"] = 22          # change a value
print(student.get("phone", "not given"))   # get() with a default, no error if missing

Loop over keys and values together with .items():

for key, value in student.items():
    print(key, value)

Counting with a dictionary

This is a very common pattern:

counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)    # {'b': 1, 'a': 3, 'n': 2}

Your task

Read a word and print how many times each character appears, in the order the characters first appear. For hello:

h 1
e 1
l 2
o 1