合并2个字典,并删除重复元素并减去重复元素的键值

时间:2019-02-01 03:40:41

标签: python

我有2个文本文件,在其中存储字典值并读取它。 所以我要读取file1.txt并将值存储在计数器变量中,而对于file2.txt我要将值存储在counter1变量中。 当我在打印counter和counter1时,会显示以下输出。

counter= {'laptop': 5, 'chair':6 , 'tv': 3}

counter1= {'laptop': 2, 'chair': 4, 'tv': 4,'plant':2}

p = len(计数器)  对于范围为(0,p)的z:

        if (list(counter.values())[v]!=list(counter1.values())[v]):

            print("Objects value on main list %s and Second List %s  "%(list(counter.items())[v],list(counter1.items())[v]))
        else:
             pass
      v=v+1

我想退货:

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

减去counter和counter1的值并打印结果。

2 个答案:

答案 0 :(得分:0)

使用此

counter= {'laptop': 5, 'chair':6 , 'tv': 3}
counter1= {'laptop': 2, 'chair': 4, 'tv': 4,'plant':2}
out = []
for key, val in counter.items():
    if key in counter1:
        out.append({key:abs(val-counter1[key])})
    else:
        out.append({key:val})
for key, val in counter1.items():
    if key not in counter:
        out.append({key:val})
print(out)

答案 1 :(得分:0)

counter= {'laptop': 5, 'chair':6 , 'tv': 3}
counter1= {'laptop': 2, 'chair': 4, 'tv': 4,'plant':2}
out = [{key : abs(counter1[key] - counter[key])} if ((key in counter) and (key in counter1)) else {key : counter[key]} if (key in counter) else {key:counter1[key]} for key in set(counter.keys() + counter1.keys())]
print out

似乎可以在1行中完成,这应该可以工作。