Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
jake77 Avatar asked Sep 21 '17 13:09

jake77


People also ask

How do I iterate a list of dictionaries in Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.

How do you write a dictionary in Python?

Creating Python Dictionary Creating a dictionary is as simple as placing items inside curly braces {} separated by commas. An item has a key and a corresponding value that is expressed as a pair (key: value).


1 Answers

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.

like image 59
Daniel Roseman Avatar answered Sep 25 '22 21:09

Daniel Roseman