我有词典列表,例如:
my_dict = [
{"name": "Al", "age": 10, "id": 1},
{"name": "Bert", "age": 15, "id": 2},
{"name": "Charles", "age": 17, "id": 3}
]
我需要仅包含'name'
和'id'
键的字典列表。
答案 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}
]