简体   繁体   中英

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.

Use an outer list comprehension:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM