3.8.3. Looping through a dictionary’s entries#
Similarly to lists, we can loop through every element of a dictionary using the for
instruction. The variable returned by for
is the key. For example, to loop over every keys of this dictionary:
dict_of_anything = {
1: "String for integer key 1",
2: "String for integer key 2",
"three": "String for string key 'three'",
"some_int_value": 10,
"some_float_value": 10.0,
"some_list": [1, 3, 5, 7],
"some_nested_dict": {
"a": "A",
"b": "B",
},
}
we would do:
for key in dict_of_anything:
print(f"Key {key} contains this value: {dict_of_anything[key]}")
Key 1 contains this value: String for integer key 1
Key 2 contains this value: String for integer key 2
Key three contains this value: String for string key 'three'
Key some_int_value contains this value: 10
Key some_float_value contains this value: 10.0
Key some_list contains this value: [1, 3, 5, 7]
Key some_nested_dict contains this value: {'a': 'A', 'b': 'B'}