Python字典列表合并

Python字典列表合并,第1张

概述我想在列表中加入词典,其关键“用户”是相同的,但我没有意识到如何.例如: [{'count2': 34, 'user': 2}, {'count4': 233, 'user': 2}, {'count2': 234, 'user': 4}, {'count4': 344, 'user': 5}] 会成为: [{'count2': 34, 'count4': 233, 'user': 2 }, 我想在列表中加入词典,其关键“用户”是相同的,但我没有意识到如何.例如:

[{'count2': 34,'user': 2},{'count4': 233,{'count2': 234,'user': 4},{'count4': 344,'user': 5}]

会成为:

[{'count2': 34,'count4': 233,'user': 2 },'user': 5}]

我广泛搜索没有发现堆栈溢出类似的东西,任何帮助将不胜感激.

@R_502_6120@ 这样的事情应该有效.但是可能有更有效的方法(并且在更少的行中)……

# inputa=[{'count2': 34,'user': 5}]# Get set of unique usersu=List(set([x['user'] for x in a]))# Create a blank List of dictionarIEs for the resultr=[{}] * len(u)# Iterate over input and add the dictionarIEs togetherfor x in a:    r[u.index(x['user'])] = dict(r[u.index(x['user'])].items() + x.items())>>> r[{'count2': 34,'user': 2,'count4': 233},'user': 5}]
总结

以上是内存溢出为你收集整理的Python字典列表合并全部内容,希望文章能够帮你解决Python字典列表合并所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1194640.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存