Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

CODE:

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

OUTPUT:

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

In case we want to preserve more than one key:

input_dicts = [
    {"name": "Al", "age": 40, "level": "junior"},
    {"name": "Bert", "age": 30, "level": "mid"},
    {"name": "Charles", "age": 20, "level": "senior"}
]

selected_keys = ("name", "level")

[
    {key: value for key, value in a_dict.items() if key in selected_keys}
    for a_dict in input_dicts
]
[{'name': 'Al', 'level': 'junior'},
 {'name': 'Bert', 'level': 'mid'},
 {'name': 'Charles', 'level': 'senior'}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top