如何将具有多个值的列表转换为列表字典

时间:2019-12-11 14:06:34

标签: python python-3.x list dictionary key-value

我有一个如下列表:

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,然后将它们附加到如下所示的新列表中。


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是一个列表,但现在在理想输出中我希望将其作为字典)

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

3 个答案:

答案 0 :(得分:2)

您很可能想要一个列表字典。这是使用itertools.groupby的一种方法:

from itertools import groupby
from operator import itemgetter

{k:[i[1] for i in list(v) if i[2]>0.] for k,v in groupby(Lista, key=itemgetter(0))}

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

注意:仅当连续的键相同时,此方法才有效

答案 1 :(得分:2)

您可以使用defaultdict

from collections import defaultdict

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)]

dct = defaultdict(list)

for item in Lista:
    key, value, score = item
    if score > 0.0:
        dct[key].append(value)

print(dct)

哪个产量

defaultdict(<type 'list'>, {
    'alien': ['dell'], 
    'amazon': ['Amazon', 'Alexa', 'microsoft', 'Amazon Pay', 'Prime']
})

Python中,您的初始请求-具有多个相同键的字典是不可能的。

答案 2 :(得分:2)

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

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

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