Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple values in Python map?

I have a list of dicts:

>>> adict = {'name': 'John Doe', 'age': 18}
>>> bdict = {'name': 'Jane Doe', 'age': 20}
>>> l = []
>>> l.append(adict)
>>> l.append(bdict)
>>> l
[{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}]

Now I want to split up the values of each dict per key. Currently, this is how I do that:

>>> for i in l:
...     name_vals.append(i['name'])
...     age_vals.append(i['age'])
...
>>> name_vals
['John Doe', 'Jane Doe']
>>> age_vals
[18, 20]

Is it possible to achieve this via map? So that I don't have to call map multiple times, but just once?

name_vals, age_vals = map(lambda ....)
like image 677
John Doe Avatar asked Dec 14 '22 18:12

John Doe


1 Answers

A simple & flexible way to do this is to "transpose" your list of dicts into a dict of lists. IMHO, this is easier to work with than creating a bunch of separate lists.

lst = [{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}]
out = {}
for d in lst:
    for k, v in d.items():
        out.setdefault(k, []).append(v)

print(out)

output

{'age': [18, 20], 'name': ['John Doe', 'Jane Doe']}

But if you really want to use map and separate lists on this there are several options. Willem has shown one way. Here's another.

from operator import itemgetter

lst = [{'age': 18, 'name': 'John Doe'}, {'age': 20, 'name': 'Jane Doe'}]
keys = 'age', 'name'
age_lst, name_lst = [list(map(itemgetter(k), lst)) for k in keys]
print(age_lst, name_lst)

output

[18, 20] ['John Doe', 'Jane Doe']

If you're using Python 2, then the list wrapper around the map call isn't necessary, but it's a good idea to use it to make your code compatible with Python 3.

like image 93
PM 2Ring Avatar answered Dec 17 '22 23:12

PM 2Ring