Richard
Richard

Reputation: 65560

python map array of dictionaries to dictionary?

I've got an array of dictionaries that looks like this:

[
  { 'country': 'UK', 'city': 'Manchester' },
  { 'country': 'UK', 'city': 'Liverpool' },
  { 'country': 'France', 'city': 'Paris' } ...
]

And I want to end up with a dictionary like this:

{ 'Liverpool': 'UK', 'Manchester': 'UK', ... }

Obviously I can do this:

 d = {}
 for c in cities:
     d[c['city']] = c['country']

But is there any way I could do it with a single-line map?

Upvotes: 7

Views: 4567

Answers (1)

Kasravnd
Kasravnd

Reputation: 107347

You can use a dict comprehension :

>>> li = [
...   { 'country': 'UK', 'city': 'Manchester' },
...   { 'country': 'UK', 'city': 'Liverpool' },
...   { 'country': 'France', 'city': 'Paris' }
... ]

>>> {d['city']: d['country'] for d in li}
{'Paris': 'France', 'Liverpool': 'UK', 'Manchester': 'UK'}

Or us operator.itemgetter and map function :

>>> dict(map(operator.itemgetter('city','country'),li))
{'Paris': 'France', 'Liverpool': 'UK', 'Manchester': 'UK'}

Upvotes: 11

Related Questions