Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Richard Avatar asked Jul 27 '15 15:07

Richard


People also ask

Can I use map on dictionary Python?

We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. map() returns a map object (an iterator), which we can use in other parts of our program.

Can you have an array of dictionaries?

Creating an Array of DictionariesAn array of dictionaries is no different. The array literal is a bit more complex, but that is the only difference. In this example, we create an array of dictionaries using an array literal. We don't need to specify the type of the array thanks to type inference.

Can Python dictionary have arrays?

Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.


1 Answers

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'}
like image 96
Mazdak Avatar answered Sep 28 '22 03:09

Mazdak