Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of dictionaries projection, filter, or subset?

I'm trying to create what I think is a 'projection' from a larger dictionary space onto a smaller dimension space. So, if I have:

mine = [
{"name": "Al", "age": 10},
{"name": "Bert", "age": 15},
{"name": "Charles", "age": 17}
]

I'm trying to find a functional expression to return only:

[
{"name": "Al"},
{"name": "Bert"},
{"name": "Charles"}
]

I've tried...

>>> filter(lambda x: x['name'],mine)
[{'age': 10, 'name': 'Al'}, {'age': 15, 'name': 'Bert'}, {'age': 17, 'name': 'Charles'}]
>>> map(lambda x : x['name'],mine)
['Al', 'Bert', 'Charles']

But seem to still be missing the right function. I know how to do it with a list comprehension, but would like to do learn how to do this functionally.

like image 666
Mittenchops Avatar asked Dec 05 '22 10:12

Mittenchops


2 Answers

Sounds like a job for list comprehensions, whether you like them or not.

>>> [{"name": d["name"]} for d in mine]
[{'name': 'Al'}, {'name': 'Bert'}, {'name': 'Charles'}]

The solution without a list comprehension would require an additional function definition:

def project(key, d):
    return {k: d[k]}

map(partial(project, "name"), mine)

Or a lambda (yuck):

map(lambda d: {"name": d["name"]}, mine)
like image 146
Fred Foo Avatar answered Dec 30 '22 10:12

Fred Foo


CODE:

print([{'name': d['name']} for d in mine])

OUTPUT:

[{'name': 'Al'}, {'name': 'Bert'}, {'name': 'Charles'}]
like image 20
Peter Varo Avatar answered Dec 30 '22 08:12

Peter Varo