Mittenchops Mittenchops - 1 year ago 92
Python Question

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.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download