7

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?

1 Answer 1

11

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'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.