首页 > 解决方案 > 如何在列表格式的字典中获取结果

问题描述

我有以下代码

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)

这给出了输出

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

如何通过对上述代码进行最小更改来获得以下格式的输出。

期望的输出


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

标签: pythonpython-3.xlistdictionarykey-value

解决方案


首先,由于您希望输出为 a dict,因此不应将其启动为list. 在我们的循环中,我们应该为每个人创建新的,而不是添加新dict的,以便result稍后将新的项目添加到它。变量名也不应该是大写的(类应该这样命名),所以可以重命名为.listkeyListamy_list

my_list = [('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)]
result = {}

for items in my_list:
    if items[2] > 0:
        if items[0] not in result:
            result[items[0]] = [items[1]]
        else:
            result[items[0]].append(items[1])
print(result)

输出:

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

推荐阅读