Python for loop over a dictionary
Jeeze, just had to remind myself of this. I got the blog up and going again to be able to note stuff like this down so here we go.
For loops on a dictionary in Python. There’s an option of looping over it raw, or include the use of its methods: keys()
, values()
, items()
.
When looping over it raw, you just get the keys back (makes me wonder why keys()
exists in the first place, but that’s a lesson for another day):
>>> myDictionary = {'a':'123','b':'456','c':'789'}
>>>
>>> for item in myDictionary:
... print(item)
...
a
b
c
You can see we get the same thing if we use .keys()
:
>>> for item in myDictionary.keys():
... print(item)
...
a
b
c
We can iterate over only its values:
>>> for item in myDictionary.values():
... print(item)
...
123
456
789
Lastly we can use items()
to get the full dataset:
>>> for item in myDictionary.items():
... print(item)
...
('a', '123')
('b', '456')
('c', '789')
The bonus with this though is that because this is a dictionary in which there are multiple items being presented, you can perform a multiple assignment like a, b = 0, 1
where a
becomes 0
and b
becomes 1
:
>>> for key, value in myDictionary.items():
... print(f'key: {key}, value: {value}')
...
key: a, value: 123
key: b, value: 456
key: c, value: 789