Search code examples
pythonpython-3.xlist-comprehensionargument-unpacking

python - iterating list of dictionaries and unpacking


Given a flat list of simple dictionaries

lst = [{'key1': 1}, {'key2': 2}, {'key3': 3}]

I'd like to find the dict that yields the minimum value evaluated using a method not detailed here. My first idea was to iterate the list to check dict by dict, but this fails:

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

results ValueError (as well as using a generator instead of the list):

for k, v in [x.items() for x in lst]:
ValueError: not enough values to unpack (expected 2, got 1)

However,

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

yields

key1 1
key2 2
key3 3

As expected. I assume all approaches work as intended (unless PEBKAC), but why doesn't it work using the list comprehension? Could someone enlighten me?

Edit: I use python 3 and I know items() yields a dict_view but I don't see why the logic doesn't work.


Solution

  • You're missing a level of iteration.

    Normally, dicts have more than one key/value pair. dict.items() converts the entire dictionary into a sequence of tuples in the form (key, value). In your case, each dictionary has just one item, but the result of items() is still a tuple of tuples.

    If you print the result of [x.items() for x in lst] you'll see that the result is a list of dict_view items; each one of those can itself be iterated.