Looping over a Dictionary
When you loop through a dictionary, you only get the keys by default.
Looping over keys
person = {"name": "Alice", "age": 16, "city": "San Francisco"}
for key in person:
print(key)
# name
# age
# cityYou can use the key to access each value inside the loop:
for key in person:
print(key, ":", person[key])
# name : Alice
# age : 16
# city : San FranciscoLooping over values
Use .values() if you only need the values:
for value in person.values():
print(value)
# Alice
# 16
# San FranciscoLooping over keys and values together
Use .items() to get both at once. Each pair comes back as a tuple (key, value):
for key, value in person.items():
print(key, ":", value)
# name : Alice
# age : 16
# city : San Francisco.items() is the most common way to loop over a dictionary when you need both the key and the value.
Try it out
main.py
Output
Last updated on