从具有重复值的字典中,如何创建一个不包含重复的新字典,并在字典中增加一个计数器? [英] From a dictionary with repeated values, how to create a new one excluding the repeats and incrementing a counter inside the dictionary?

查看:161
本文介绍了从具有重复值的字典中,如何创建一个不包含重复的新字典,并在字典中增加一个计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = {'1': {'name': 'Blue', 'qty': '1'},
     '2': {'name': 'Green', 'qty': '1'},
     '3': {'name': 'Blue', 'qty': '1'},
     '4': {'name': 'Blue', 'qty': '1'}}

进入此:

b = {'1': {'name': 'Blue', 'qty': '3'},
     '2': {'name': 'Green', 'qty': '1'}}

我能够排除重复的值,但是不能增加'qty'字段.

I was able to exclude the repeated values but could't increment the 'qty' field.

b = {}

for k,v in a.iteritems():
    if v not in b.values():
        b[k] = v

推荐答案

这似乎可行:

from collections import defaultdict

result = defaultdict(lambda: 0)

# Summarize quantities for each name
for item in a.values():
    result[item['name']] += int(item['qty'])

# Convert to your funny format
b = {str(i+1): v for i, v in enumerate({'name': key, 'qty': str(val)} for key, val in result.items())}

# b contains:
# {'1': {'name': 'Blue', 'qty': '3'}, '2': {'name': 'Green', 'qty': '1'}}

如果我可以选择数据结构,它可能看起来像这样:

If I could choose data structures, it might look like this:

from operator import add
from collections import Counter

a = [('Blue', 1), ('Green', 1), ('Blue', 1), ('Blue', 1)]
b = reduce(add, [Counter(**{x[0]: x[1]}) for x in a])
# b contains:
# Counter({'Blue': 3, 'Green': 1})

这篇关于从具有重复值的字典中,如何创建一个不包含重复的新字典,并在字典中增加一个计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆