从列表中删除重复的字典,并减去重复元素的键值

时间:2019-01-31 11:17:50

标签: python list dictionary

我有一个字典列表,我想用相同的键删除字典并减去值对。

对于此列表:

[{'chair': 4}, {'tv': 5}, {'chair': 3}, {'tv': 2}, {'laptop': 2}]

我想退货:

[{'chair': 1}, {'tv': 3}, {'laptop': 2}]

4 个答案:

答案 0 :(得分:3)

您可以这样做,为效率创建一个中间指标:

dicts_list = [{'chair': 4}, {'tv': 5}, {'chair': 3}, {'tv': 2}, {'laptop': 2}]

out = {}
for d in dicts_list:
    for key, val in d.items():
       if key in out:
           out[key] -= val
       else:
           out[key] = val

out_list = [ {key:val} for key, val in out.items()]

print(out_list)
# [{'tv': 3}, {'chair': 1}, {'laptop': 2}]

但是您可能会对这个中间字典作为输出感兴趣:

print(out)
# {'tv': 3, 'chair': 1, 'laptop': 2}

答案 1 :(得分:1)

集合中的

defaultdict可能会派上用场。此解决方案将解决列表中同一键的字典超过2个字典的情况。

from collections import defaultdict
ls = defaultdict(list)
d = [{'chair': 4}, {'tv': 5}, {'chair': 3}, {'tv': 2}, {'laptop': 2}]


# Creating a list of all values under one key

for dic in d:
    for k in dic:
            ls[k].append(dic[k])

print(ls)
defaultdict(<class 'list'>, {'chair': [4, 3], 'tv': [5, 2], 'laptop': [2]})

# safe proofing for negative values on subtraction    
for k in ls:
    ls[k].sort(reverse=True)
    ls[k] = ls[k][0] - sum(ls[k][1:])

print(ls)
defaultdict(<class 'list'>, {'chair': 1, 'tv': 3, 'laptop': 2})

答案 2 :(得分:0)

以下代码段仅使用标准模块:

a= [{'chair': 4}, {'tv': 5}, {'chair': 3}, {'tv': 2}, {'laptop': 2}]

print("Input:", a)

b=dict()
for element in a:
    for k,v in element.items():
        try:
          # you didn't specify the subtracted element order,   
          # so I'm subtracting BIGGER from SMALLER using simple abs() :)
          b[k] = abs(b[k] - v) 
        except:
          b[k] = v

print("Output:", b)

# restore original structure
c = [ dict({item}) for item in b.items() ]

print("Output:", c)

演示:

('Input:', [{'chair': 4}, {'tv': 5}, {'chair': 3}, {'tv': 2}, {'laptop': 2}])
('Output:', {'tv': 3, 'chair': 1, 'laptop': 2})
('Output:', [{'tv': 3}, {'chair': 1}, {'laptop': 2}])

编辑:添加了辅助输出C来重组B,类似于A

答案 3 :(得分:0)

您可以构建列表的defaultdict,然后使用列表理解:

from collections import defaultdict

dd = defaultdict(list)
for d in data:
    k, v = next(iter(d.items()))
    dd[k].append(v)

res = [{k: v if len(v) == 1 else v[0] - sum(v[1:])} for k, v in dd.items()]

print(res)
# [{'chair': 1}, {'tv': 3}, {'laptop': [2]}]