过滤最终列表中包含特定键的词典列表

时间:2017-10-22 12:02:55

标签: python dictionary projection

我有词典列表,例如:

my_dict = [
    {"name": "Al", "age": 10, "id": 1},
    {"name": "Bert", "age": 15, "id": 2},
    {"name": "Charles", "age": 17, "id": 3}
]

我需要仅包含'name''id'键的字典列表。

1 个答案:

答案 0 :(得分:1)

您可以使用以下列表理解 dict comprehension 表达式的组合来执行此操作:

my_dict_list = [
     {"name": "Al", "age": 10, "id": 1},
     {"name": "Bert", "age": 15, "id": 2},
     {"name": "Charles", "age": 17, "id": 3}
]

# Set of keys you want to filter in new list
new_keys = {"id", "name"}

new_dict_list = [{k: d.get(k) for k in new_keys} for d in my_dict_list]
#                       ^ To fill the value as `None` if key not present
#                         in any intermediate dict

其中new_dict_list将保留值:

>>> new_dict_list
[
     {'name': 'Al', 'id': 1}, 
     {'name': 'Bert', 'id': 2}, 
     {'name': 'Charles', 'id': 3}
]