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': 'Ber
Solution 1:
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)
Solution 2:
CODE:
print([{'name': d['name']} for d in mine])
OUTPUT:
[{'name': 'Al'}, {'name': 'Bert'}, {'name': 'Charles'}]
Solution 3:
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'}]
Post a Comment for "Python List Of Dictionaries Projection, Filter, Or Subset?"