Home > Enterprise >  Python dictionary comprehension on a list of dictionaries
Python dictionary comprehension on a list of dictionaries

Time:12-19

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.

CodePudding user response:

Use an outer list comprehension:

list_you_want = [{k: d[k] for k in your_keys} for d in orig_list]
  • Related