繁体   English   中英

如何使用 Python 中的特定键从字典列表中创建字典

[英]How to create a dictionary from a list of dictionary using specific keys in Python

我需要从字典列表中提取特定的键:值,然后在 Python 中创建一个“新字典”。

我知道如何从单个字典中创建一个“新字典”(提取键“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:

{'a': 1, 'c': 3}

但是,如果我有这样的字典列表:

# 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'}]

如何提取和 output 键“a”和“c”及其相关值,如下所示:

[{'a': 1, 'c': 3}, {'a': 100, 'c': 300}, {'a': 'Apple', 'c': 'Cat'}]

我试过这个:

d22 = dict((k, d2[k])
           for k in ["a", "c"] if k in d2)

但它返回一个空字典:

{}

尝试使用:

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)

打印:

[{'a': 1, 'c': 3}, {'a': 100, 'c': 300}, {'a': 'Apple', 'c': 'Cat'}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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