排除字典中的重复值,并相应地增加“数量”字段 [英] Exclude repeated values from a dictionary and increment the 'qty' field accordingly
问题描述
考虑到1,2,3,4是索引,其他所有其他作为Python中的字典的值,我试图排除重复的值并增加数量字段发现重复。例如:
Considering '1', '2', '3', '4' are the indexes and everything else as the values of a dictionary in Python, I'm trying to exclude the repeating values and increment the quantity field when a dupicate is found. e.g.:
a = {'1': {'name': 'Blue', 'qty': '1', 'sub': ['sky', 'ethernet cable']},
'2': {'name': 'Blue', 'qty': '1', 'sub': ['sky', 'ethernet cable']},
'3': {'name': 'Green', 'qty': '1', 'sub': []},
'4': {'name': 'Blue', 'qty': '1', 'sub': ['sea']}}
到这个:
into this:
b = {'1': {'name': 'Blue', 'qty': '2', 'sub': ['sky', 'ethernet cable']},
'2': {'name': 'Green', 'qty': '1', 'sub': []},
'3': {'name': 'Blue', 'qty': '1', 'sub': ['sea']}}
我能够排除重复,但我很难增加数量字段:
I was able to exclude the duplicates, but I'm having a hard time incrementing the 'qty' field:
b = {}
for k,v in a.iteritems():
if v not in b.values():
b[k] = v
PS:我提前发布了这个问题,但是忘了添加字典可以有一个列表的'sub'字段。另外,不要介意奇怪的字符串索引。
P.S.: I posted this question earlier, but forgot to add that the dictionary can have that 'sub' field which is a list. Also, don't mind the weird string indexes.
推荐答案
首先,转换原来的dict '
和'sub'
键以逗号分隔的字符串,因此我们可以使用 set()
:
First, convert the original dict 'name'
and 'sub'
keys to a comma-delimited string, so we can use set()
:
data = [','.join([v['name']]+v['sub']) for v in a.values()]
返回
['Blue,sky,ethernet cable', 'Green', 'Blue,sky,ethernet cable', 'Blue,sea']
然后使用嵌套的dict和列表推导如下:
Then use the nested dict and list comprehensions as below:
b = {str(i+1): {'name': j.split(',')[0], 'qty': sum([int(qty['qty']) for qty in a.values() if (qty['name']==j.split(',')[0]) and (qty['sub']==j.split(',')[1:])]), 'sub': j.split(',')[1:]} for i, j in enumerate(set(data))}
这篇关于排除字典中的重复值,并相应地增加“数量”字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!