Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python dictionary comprehension on a list of dictionaries

I have a list of dictionaries. Each dictionary has a large number of keys.
I want to just keep certain keys that I already know, let’s say keys ‘a’, ‘b’, ‘c’. Each dict will have these keys.

I know how to do it on a single dictionary based on another stack overflow post:

your_keys = ['a', 'b', 'c']
dict_you_want = {your_key: orig_dict[your_key] for your_key in your_keys}
# Example Input
orig_list = [
    {"name": "bob", "age": 23, "city": "Atlanta"},
    {"name": "carl", "age": 48, "city": "Austin"}]
your_keys = ['name', 'age']

# Example Output
list_you_want = [{"name": "bob", "age": 23}, {"name": "carl", "age": 48}]

I am not sure how to do it for a list of dicts though.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use an outer list comprehension:

list_you_want = [{k: d[k] for k in your_keys} for d in orig_list]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading