如何将具有多个值的列表转换为列表字典 [英] How to convert a list having multiple values into a dictionary of lists

查看:451
本文介绍了如何将具有多个值的列表转换为列表字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下列表:

Lista =[('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7), ('amazon', 'Prime', 0.4),('alien', 'jack' , 0.0), ('alien', 'dell', 0.6), ('alien', 'apple', 0.0), ('alien', 'orange', 0.0), ('alien', 'fig', 0.0)]

现在,我正在执行基本检查,以查看哪些对的值大于0.0,然后将它们附加到如下所示的新列表中.

Now I am performing a basic check to see which pairs have value greater than 0.0 and then append them to a new list like below.


new_words = []

Lista =[('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7), ('amazon', 'Prime', 0.4),('alien', 'jack' , 0.0), ('alien', 'dell', 0.6), ('alien', 'apple', 0.0), ('alien', 'orange', 0.0), ('alien', 'fig', 0.0)]

for x in Lista:
    if x[2]>0:
    new_words.append(x[1])

我的问题是如何将结果附加到具有相应键,值对的字典中.所需的理想输出如下:(请注意,先前的new_words是一个列表,但现在在理想输出中我希望将其作为字典)

My question is how do I append the results in a dictionary with respective key, value pairs. Ideal output required is as below: (Please note earlier new_words was a list but now in the ideal output I want it as a dictionary)

new_words={'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime'],
 'alien': ['dell']}

推荐答案

您无法在字典中获得所需的结果,因为字典中不包含重复的键(类似于普通的英语词典:其中的单词可能拼写相同,但发音有所不同.

You can't have the desired result in a dictionary as dictionaries don't contain duplicate keys (similar to a normal English dictionary: where the words might spell the same but there are differences in pronunciation).

所需结果可以再次存储到列表中.

The desired result can be stored again into a list.

newDict = {}
result = []

Lista =[('amazon', 'Amazon', 1.0), ('amazon', 'Alexa', 0.8), ('amazon', 'microsoft', 0.6), ('amazon', 'Amazon Pay', 0.7), ('amazon', 'Prime', 0.4),('alien', 'jack' , 0.0), ('alien', 'dell', 0.6), ('alien', 'apple', 0.0), ('alien', 'orange', 0.0), ('alien', 'fig', 0.0)]

for items in Lista:
    if items[2] > 0.0:
        newDict[items[0]] = items[1]
        result.append(newDict)
        newDict = {}

print result

这篇关于如何将具有多个值的列表转换为列表字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆