简体   繁体   English

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

[英]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.

相关问题 如何用Python中的键列表和值字典创建字典? - How to create a dictionary from a list of keys and a dictionary of values in Python? 如何从 Python 中的字典中提取特定键的列表? - How to extract list of specific keys from the dictionary in Python? 如何从具有特定属性的字典中打印键列表 - How to print a list of keys from a dictionary with a specific 如何从嵌套字典创建包含子字典键的列表? - How to create a List containing a sub dictionary keys , from nested dictionary? 如何使用两个相同的键和不同的值从 Python 中的三个不同列表创建字典? - How to create dictionary from three different list in Python using two same Keys and different values? 如何使用以前词典中的键和值创建词典? - How to Create a Dictionary Using Keys and Values from a Previous Dictionary? 如何使用 2 个列表中的 python 列表理解创建字典 - How to create a dictionary using python list comprehension from 2 list 如何将列表列表中的值分配给键以在 python 中创建字典 - How to assign values in list of list to keys to create dictionary in python Python:map 字典键与列表中的值以使用 for 循环创建新列表 - Python: map dictionary keys with values from a list to create a new list using for loop 如何创建从具有多个键的 Python 字典中输出特定键值的 Python 程序? - How to Create a Python Program that Outputs a Specific Key Value from a Python Dictionary that has Multiple Keys?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM