Python dictionary comprehension on a list of dictionaries

Question:

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.

Asked By: Columbus

||

Answers:

Use an outer list comprehension:

list_you_want = [{k: d[k] for k in your_keys} for d in orig_list]
Answered By: wjandrea
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.