TIL: Iterating Through Python Dictionary

Somehow I’ve been working with python for 2 years now and never knew this was a thing. Wow.

So usually when I used to loop through dictionaries, I’d just do something simple like….

1
2
3
4
5
6
7
8
a = {
 "a": 123,
 "b": 456,
 "c": 789
}

for i in a:
 print(i, a[i])

But it always required that extra step when trying to reference to the value in the key-value-pair. So much to my surprise (although I guess it really shouldn’t have been…), there’s a much cleaner way to do this same thing using the .items() dictionary method:

1
2
3
4
5
6
7
8
a = {
 "a": 123,
 "b": 456,
 "c": 789
}

for i,j in a.items():
 print(i, j)

This gives full access to both the key and value by variable name, rather than having to chain the key to the dictionary to get the value.

💚