Skip to main content
 首页 » 编程设计

python之从字典中排除重复值并相应地增加 'qty' 字段

2025年05月04日13pander-it

考虑到 '1'、'2'、'3'、'4' 是索引,其他所有内容都作为 Python 中字典的值,我试图排除重复值并在发现重复。例如:

打开这个:

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']}} 

进入这个:

b = {'1': {'name': 'Blue', 'qty': '2', 'sub': ['sky', 'ethernet cable']}, 
     '2': {'name': 'Green', 'qty': '1', 'sub': []}, 
     '3': {'name': 'Blue', 'qty': '1', 'sub': ['sea']}} 

我能够排除重复项,但我很难增加“数量”字段:

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

P.S.:我之前发布了这个问题,但忘记补充说字典可以有一个“子”字段,它是一个列表。另外,不要介意奇怪的字符串索引。

请您参考如下方法:

首先,将原始字典的 'name' 和 'sub' 键转换为逗号分隔的字符串,这样我们就可以使用 set():

data = [','.join([v['name']]+v['sub']) for v in a.values()] 

返回

['Blue,sky,ethernet cable', 'Green', 'Blue,sky,ethernet cable', 'Blue,sea'] 

然后使用嵌套的字典和列表理解如下:

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))}