Like integer ranges and lists, dictionaries are iterable.
fruit_basket = {'apple': 5, 'banana': 3, 'cherry': 10}
for key in fruit_supply:
print(f"The basket contains pieces of {key}")
This code runs over all keys in the dictionary and prints:
The basket contains pieces of apple
The basket contains pieces of banana
The basket contains pieces of cherry
In order to get both key and value, use the items
method of the dictionary class:
fruit_basket = {'apple': 5, 'banana': 3, 'cherry': 10}
for key,val in fruit_supply.items():
print(f"There are {val} pieces of {key} in the basket")
This code runs over all key-value pairs in the dictionary and prints:
There are 5 pieces of apple in the basket
There are 3 pieces of banana in the basket
There are 10 pieces of cherry in the basket