Python字典列表合并
发布时间:2020-12-20 12:20:32 所属栏目:Python 来源:网络整理
导读:我想在列表中加入词典,其关键“用户”是相同的,但我没有意识到如何.例如: [{'count2': 34,'user': 2},{'count4': 233,{'count2': 234,'user': 4},{'count4': 344,'user': 5}] 会成为: [{'count2': 34,'count4': 233,'user': 2 },'user': 5}] 我广泛搜索没
我想在列表中加入词典,其关键“用户”是相同的,但我没有意识到如何.例如:
[{'count2': 34,'user': 2},{'count4': 233,{'count2': 234,'user': 4},{'count4': 344,'user': 5}] 会成为: [{'count2': 34,'count4': 233,'user': 2 },'user': 5}] 我广泛搜索没有发现堆栈溢出类似的东西,任何帮助将不胜感激. 解决方法
这样的事情应该有效.但是可能有更有效的方法(并且在更少的行中)……
# Input a=[{'count2': 34,'user': 5}] # Get set of unique users u=list(set([x['user'] for x in a])) # Create a blank list of dictionaries for the result r=[{}] * len(u) # Iterate over input and add the dictionaries together for 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}] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |