[英]How to create a dictionary from a list of dictionary using specific keys in Python
I need to extract specific keys:values from a list of dictionary and then create a 'new dictionary' in Python.我需要从字典列表中提取特定的键:值,然后在 Python 中创建一个“新字典”。
I know how to create a 'new dictionary' from a single dictionary (extracting keys 'a' and 'c' and their associated values):我知道如何从单个字典中创建一个“新字典”(提取键“a”和“c”及其相关值):
# Single dictionary
d1 = {"c": 3, "a": 1, "b": 2, "d": 4}
d11 = dict((i, d1[i])
for i in ["a", "c"] if i in d1)
print(d11)
Output: Output:
{'a': 1, 'c': 3}
But if I have a list of dictionary like this:但是,如果我有这样的字典列表:
# List of dictionary
d2 = [{"c": 3, "a": 1, "b": 2, "d": 4},
{"a": 100, "c": 300, "b": 200, "d": 400},
{"b": 'Ball', "c": 'Cat', "d": 'Doll', "a": 'Apple'}]
How can I extract and output the keys 'a' and 'c' and their associated values like this:如何提取和 output 键“a”和“c”及其相关值,如下所示:
[{'a': 1, 'c': 3}, {'a': 100, 'c': 300}, {'a': 'Apple', 'c': 'Cat'}]
I have tried this:我试过这个:
d22 = dict((k, d2[k])
for k in ["a", "c"] if k in d2)
But it returns an empty dictionary:但它返回一个空字典:
{}
Try to use:尝试使用:
d2 = [{"c": 3, "a": 1, "b": 2, "d": 4},
{"a": 100, "c": 300, "b": 200, "d": 400},
{"b": 'Ball', "c": 'Cat', "d": 'Doll', "a": 'Apple'}]
filter_list = ["a", "c"]
d22 = [{k: d[k] for k in filter_list} for d in d2]
print(d22)
Print:打印:
[{'a': 1, 'c': 3}, {'a': 100, 'c': 300}, {'a': 'Apple', 'c': 'Cat'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.