如何从 Python 列表中的字典中提取键和值?例如:list1 = ["john", 10, 20, {"joe":50, "robert";60}] [关闭]

问题描述 投票:0回答:4

如何从 Python 列表中的字典中提取键和值?

例如:

list1 = ["john", 10, 20, {"joe":50, "robert";60}]

如何用上面列表中字典的值创建一个新列表?

python
4个回答
1
投票

查找字典 - 知道它在给定列表中的索引

如果要创建提及字典的值的列表,则需要先获取字典。如果您知道字典在哪里 - 您提供的示例 - 或者如果您需要使用 sigmapie8 的答案 找到它,就可以做到这一点。

提取字典,将其值放入新列表

假设我们知道想要的字典是给定列表中的第 4 个元素,我们可以使用从零开始的索引访问它,如

list1[3]
.

一旦你有了字典,你需要使用

values()
获取它的值并将它们放入一个新列表中。

这可以在一条线上完成。我将使用您提供的示例来说明我的观点。

list1 = ["john", 10, 20, {"joe":50, "robert":60}]

new_list = list(list1[3].values())

然后您可以

print()
new_list。预期输出:

[50,60]

我相信这就是你想要做的。同样,如果您不知道您的词典在原始列表中的位置,这可以与前面提到的答案结合使用。


0
投票
list1 = ["john", 10, 20, {"joe":50, "robert":60}]

for item in list1:
  if(isinstance(item, dict)):
    print(item)
    # do whatever you want with it

0
投票

def dictionary_unpaker(列表):

"""
This function  gets a dictionary in a list and returns items of the dictionary.
"""
key_list=[]
value_list=[]
for i in list:
    dictionary={}
    if type(i)==dict:
        dictionary=i
        break
else :
     return "There isn't any dictionary in your list"      
for key,value in dictionary.items():
    key_list.append(key)
    value_list.append(value)
return value_list,key_list

-1
投票
list1 = ["john", 10, 20, {"joe":50, "robert":60}, {"ads":50, "awd":60}]
list2 = list(zip(*[[list(s.keys()), list(s.values())] for s in list1 if isinstance(s, dict)]))
print(list2)
© www.soinside.com 2019 - 2024. All rights reserved.