Jacob-Jan Mosselman
Jacob-Jan Mosselman

Reputation: 813

Loop over items in dicts in list using Python 3 comprehensions

Suppose I have a list with dicts, given is: each dict contains one key.

testlist = [{'x': 15}, {'y': 16}, {'z': 17}]

for x in testlist:
    for k, v in x.items():
        print(k,v)

# x 15
# y 16
# z 17

How can I use comprehensions to get the same result? I tried this:

for k,v in [x.items() for x in testlist]:
    print(k,v)

Returns: ValueError: not enough values to unpack (expected 2, got 1)

Upvotes: 0

Views: 30

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155363

You have to make a multiloop comprehension:

for k,v in [pair for x in testlist for pair in x.items()]:

or use itertools.chain to do the flattening for you (somewhat more efficiently):

from itertools import chain

for k, v in chain.from_iterable(x.items() for x in testlist):
# Or with operator.methodcaller to move the work to the C layer:
for k, v in chain.from_iterable(map(methodcaller('items'), testlist)):

Upvotes: 3

Related Questions