How to Iterate Over a Python Dictionary?

python

To iterate over a dictionary in Python, use the for-in loop:

d = {"a": 1, "b": 2}
for key in d:
    value = d[key]
    # do something with key and value

Alternatively, use the for loop on d.items(), which yields both the key as well as the value:

d = {"a": 1, "b": 2}
for key, value in d.items():
    # do something with key and value

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?