Iterating over dictionaries
suggest changeConsidering the following dictionary:
d = {"a": 1, "b": 2, "c": 3}
To iterate through its keys, you can use:
import json
d = {"a": 1, "b": 2, "c": 3}
for key in d:
print(json.dumps(key))
"a"
"b"
"c"
This is equivalent to:
for key in d.keys():
print(key)
To iterate through its values, use:
d = {"a": 1, "b": 2, "c": 3}
for value in d.values():
print(value)
1
2
3
To iterate through its keys and values, use:
d = {"a": 1, "b": 2, "c": 3}
for key, value in d.items():
print(key, "::", value)
a :: 1
b :: 2
c :: 3
Since Python 3.7, a dictionary preserves insertion order, so these loops print
a,b, thenc. Before that, the order was not part of the language.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents