30

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?

Worm
  • 1,313
  • 2
  • 11
  • 28
  • 8
    Unpack with a tuple -> `for i, (k, v) in enumerate(regionspointcount.items()):` – cs95 Oct 09 '17 at 22:04
  • 1
    @cᴏʟᴅsᴘᴇᴇᴅ As simple as this comment may be, it should be an answer (and not a comment). – bergerg Oct 09 '17 at 22:05
  • 2
    The “index” of a dictionary key doesn’t have any meaning, as they aren’t ordered. What’s the problem you’re really trying to solve? Also see https://stackoverflow.com/questions/42193712/how-to-iterate-dict-with-enumerate-and-unpack-the-index-key-and-value-alon – jonrsharpe Oct 09 '17 at 22:09
  • The index does matter if the dictionary is [sorted](https://www.saltycrane.com/blog/2007/09/how-to-sort-python-dictionary-by-keys/) :) – Worm Oct 09 '17 at 22:11
  • ...which yours isn’t, at least as far as the example goes. If the order matters, consider using OrderedDict or another ordered data structure. – jonrsharpe Oct 09 '17 at 22:12
  • 1
    Worm, if you're trying to hold counts, you should look at my favourite data structure: `collections.Counter`. – cs95 Oct 09 '17 at 22:13
  • Mine is @jonrsharpe and now I am selecting the first and last 30 entries. I left this information out so as not to confuse the question with too much information. Thanks to COLDSPEED I have a solution that I am happy with. – Worm Oct 09 '17 at 22:14
  • I will look into collections. Thanks @cᴏʟᴅsᴘᴇᴇᴅ :) – Worm Oct 09 '17 at 22:15
  • 1
    @Worm Asking questions that are a duplicate is NOT a crime. The duplicates serve as signposts to the original. In some cases, the duplicates receive even better answers than the original, which is a win for everyone. – cs95 Oct 09 '17 at 22:24
  • Noted @cᴏʟᴅsᴘᴇᴇᴅ. I had the impression that they were a grievous sin. Cheers for your help. – Worm Oct 09 '17 at 22:25

2 Answers2

57

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thanks, I hadn't found a way to do this online. I will accept and then +1 in 2 hours when I get new votes :) – Worm Oct 09 '17 at 22:09
  • 1
    It is useful to also know that `list(enumerate(d.items()))` will be unpacked as `[(0, ('A', 1)), (1, ('C', 3)), (2, ('B', 2)), (3, ('D', 4))]`. This is the reason behind unpacking them as seperate tuples. – Unni Oct 09 '17 at 22:09
  • 1
    @Unni, thank you. Added that in. – cs95 Oct 09 '17 at 22:14
  • 1
    This is all in https://stackoverflow.com/questions/42193712/how-to-iterate-dict-with-enumerate-and-unpack-the-index-key-and-value-alon – jonrsharpe Oct 09 '17 at 22:17
  • @jonrsharpe Thanks. Since I've answered, I don't think I should close it. Will you mark it? Also, I think it's fine to leave as a suitable dupe, the wording is different enough that it needn't be downvoted. – cs95 Oct 09 '17 at 22:18
  • I’d already have done, but I’m out of votes. – jonrsharpe Oct 09 '17 at 22:19
  • Sorry for the very similar question. I did a decent search of SO and other sites but could't find a duplicate – Worm Oct 09 '17 at 22:21
14

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.

Adrian W
  • 4,563
  • 11
  • 38
  • 52
  • OP states explicitly that he wants to enumerate (i.e. have an index number at his disposal) while iterating key-value-pairs. Thus your assumption of not needing the index i is sadly incorrect. – MA53QXR Mar 12 '20 at 12:05
  • @MA53QXR Just read the title: iterating key and value. It does _not_ say iterating key, index and value. – Adrian W Mar 12 '20 at 12:44