python - 如何在列表格式的字典中获取结果
问题描述
我有以下代码
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']}
解决方案
首先,由于您希望输出为 a dict
,因此不应将其启动为list
. 在我们的循环中,我们应该为每个人创建新的,而不是添加新dict
的,以便result
稍后将新的项目添加到它。变量名也不应该是大写的(类应该这样命名),所以可以重命名为.list
key
Lista
my_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']}
推荐阅读
- reactjs - 为什么不能根据道具反应设置初始状态
- vba - 用另一张包含有效值的表格检查一列中的单词并回填它
- sql - 统计数据不同的sql
- spring-mvc - @RefreshScope - JUnit 测试用例
- c# - 获取有关 Android 库的触摸信息
- angular - Object(...) 不是 ionic3 中使用 angularfire2 的函数
- python - 发出并发 selenium/chromedriver 请求时出现 ResponseNotReady 错误
- javascript - Express res.download 极其奇怪的行为
- c++ - 我怎样才能得到一个指向已经推导出的模板函数的指针?
- python - 加载一个 json 文件,遍历它并将每个元素写入一个新文件