Introduction
Dictionary iteration helps you look at each item in a dictionary one by one. This lets you use or change the data inside easily.
Jump into concepts and practice - no test required
Dictionary iteration helps you look at each item in a dictionary one by one. This lets you use or change the data inside easily.
for key in dictionary: # use key or dictionary[key] for key, value in dictionary.items(): # use key and value
You can loop over just keys or both keys and values.
Use .items() to get both key and value together.
my_dict = {'apple': 3, 'banana': 5}
for key in my_dict:
print(key)my_dict = {'apple': 3, 'banana': 5}
for key, value in my_dict.items():
print(f"{key} -> {value}")my_dict = {'apple': 3, 'banana': 5}
for value in my_dict.values():
print(value)This program shows how to loop over just keys and then over both keys and values in a dictionary.
fruits = {'apple': 2, 'banana': 4, 'cherry': 6}
print('Keys:')
for fruit in fruits:
print(fruit)
print('\nKeys and values:')
for fruit, count in fruits.items():
print(f'{fruit} -> {count}')Using .items() is the most common way to get both keys and values.
Looping over a dictionary without .items() gives you keys only.
Dictionary iteration lets you visit each key or each key-value pair.
Use for key in dict to get keys.
Use for key, value in dict.items() to get keys and values.
for key in my_dict:for key in my_dict, which by default iterates over dictionary keys.my_dict?my_dict.items() which returns key-value pairs.for key, value in my_dict.items(): correctly unpacks keys and values.my_dict = {'a': 1, 'b': 2}
for k, v in my_dict.items():
print(k, v)my_dict.items().my_dict = {'x': 10, 'y': 20}
for key, value in my_dict:
print(key, value)my_dict directly, which yields only keys.my_dict.items() instead of just my_dict.data = {'a': 0, 'b': 2, 'c': 0, 'd': 4}, which code snippet creates a new dictionary with only keys having non-zero values?if v != 0 in comprehension.data.items() and filters by value.