Iterating over dictionaries

suggest change

Considering 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, then c. Before that, the order was not part of the language.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents