mrgou
mrgou

Reputation: 2448

From list of dict to single dict using values as key/value pairs

From a JSON input, I have a list of dictionaries, all using the same keys:

[{'id': '1', 'country': 'Brazil'},
 {'id': '2', 'country': 'Spain'},
 {'id': '3', 'country': 'South Korea'},
 {'id': '4', 'country': 'United States'},
 {'id': '5', 'country': 'Italy'}]

Since I need an easy way to get the id value from any country name, I want to convert this into a single dictionary:

{'Brazil': 1, 'Spain': 2, 'South Korea': 3, 'United States': 4, 'Italy': 5}

I thought I could do this with a dictionary comprehension:

countries = {k:v for d in my_list for (k, v) in d.values()}

However, this yields:

ValueError: too many values to unpack (expected 2)

Which I didn't expect, since d.values() should only return two items.

What am I missing?

Upvotes: 0

Views: 65

Answers (2)

Chris Doyle
Chris Doyle

Reputation: 11992

You can get the values as a tuple and reverse it. then you can pass them to the dict call to create your new dict.

my_list = [{'id': '1', 'country': 'Brazil'},
 {'id': '2', 'country': 'Spain'},
 {'id': '3', 'country': 'South Korea'},
 {'id': '4', 'country': 'United States'},
 {'id': '5', 'country': 'Italy'}]


countries = dict(tuple(d.values())[::-1] for d in my_list)
print(countries)

OUTPUT

{'Brazil': '1', 'Spain': '2', 'South Korea': '3', 'United States': '4', 'Italy': '5'}

Upvotes: 0

crissal
crissal

Reputation: 2647

As pointed out in the comments, dict.items yield a tuple.

However, just changing values with items will overwrite your freshly generated dictionary (and furthermore, not leading to your desired result).

>>> {k:v for item in my_list for (k,v) in item.items()}
{'id': '5', 'country': 'Italy'}

Instead, you have to specify the keys you need.

>>> {item['country']:item['id'] for item in my_list}
{'Brazil': '1', 'Spain': '2', 'South Korea': '3', 'United States': '4', 'Italy': '5'}

Upvotes: 3

Related Questions