猿问

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

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


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


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

p=len(counter) for z in range (0 ,p):


        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 的值并打印结果。


墨色风雨
浏览 220回答 2
2回答

慕斯王

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 行中完成,这应该可行。

一只甜甜圈

用这个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)
随时随地看视频慕课网APP

相关分类

Python
我要回答