Enumerate Dictionary Iterating Key and Value [duplicate]

Each Answer to this Q is separated by one/two green lines.

I have a dictionary called regionspointcount that holds region names (str) as the keys and a count of a type of feature within that region (int) as the values e.g. {'Highland':21}.

I am wanting to iterate the key and value of dictionary while enumerating. Is there a way to do something like:

for i, k, v in enumerate(regionspointcount.items()):

or do I have to resort to using a count variable?

Given a dictionary d:

d
# {'A': 1, 'B': 2, 'C': 3, 'D': 4}

You can use a tuple to unpack the key-value pairs in the for loop header.

for i, (k, v) in enumerate(d.items()):
     print(i, k, v)

# 0 A 1
# 1 B 2
# 2 C 3
# 3 D 4

To understand why the extra parens are needed, look at the raw output from enumerate:

list(enumerate(d.items()))
# [(0, ('A', 1)), (1, ('B', 2)), (2, ('C', 3)), (3, ('D', 4))]

The key-value pairs are packaged inside tuples, so they must be unpacked in the same way.

Assuming you just want to enumerate the key/value pairs (and don’t need the index i), you can iterate d.items() directly:

d = {'A': 1, 'B': 2, 'C': 3, 'D': 4}
for k, v in d.items():
    print(k, v)

This prints something like

A 1
C 3
B 2
D 4

Note that entries are not necessarily ordered.


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .