John Doe
John Doe

Reputation: 145

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 ....)

Upvotes: 4

Views: 9121

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55479

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.

Upvotes: 7

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

If all dictionaries have the 'name' and 'age' key, and we can use the zip builtin, we can do this with:

from operator import itemgetter

names, ages = zip(*map(itemgetter('name', 'age'), l))

This will produce tuples:

>>> names
('John Doe', 'Jane Doe')
>>> ages
(18, 20)

In case you need lists, an additional map(list, ..) is necessary.

Upvotes: 6

Related Questions