【问题标题】:Merging 2 dictionaries and saving translation dictionary for the overridden values合并 2 个字典并为覆盖的值保存翻译字典
【发布时间】:2018-08-20 07:13:47
【问题描述】:

我合并了 2 个字典,比如 d1d2 by:

d1.update(d2)

即我有:

d1 = {1:'a', 2:'b', 3:'c'}
d2 = {1:'a', 2:'g', 4:'x'}

那么在d1.update(d2)之后我有:

{1: 'a', 2: 'g', 3: 'c', 4: 'x'}

所以原来的 2:'b' 消失了,所以我想以某种方式翻译 'b':'g',这意味着输出将是以下字典:

{'b':'g'}

是否有任何简单的代码来保留被覆盖的值?

【问题讨论】:

标签: python python-3.x dictionary merge


【解决方案1】:

如果{"b":"g}是你真正想要的,你可以先使用dict理解在update之前创建它:

d1 = {1:'a', 2:'b', 3:'c'}
d2 = {1:'a', 2:'g', 4:'x'}

ot = {v : d2[k] for k,v in d1.items() if k in d2 and v != d2[k]}
print (ot)

d1.update(d2)
print (d1)

结果:

{'b': 'g'}
{1: 'a', 2: 'g', 3: 'c', 4: 'x'}

【讨论】:

    【解决方案2】:
    1. 查找两个字典中都存在的键
    2. 创建一个新字典,将d1 中的值映射到d2 中的值
    3. 删除键和值相同的键:值对
    d1 = {1:'a', 2:'b', 3:'c'}
    d2 = {1:'a', 2:'g', 4:'x'}
    
    shared_keys = d1.keys() & d2
    mapping = {d1[key]: d2[key] for key in shared_keys}
    mapping = {k: v for k, v in mapping.items() if k != v}
    
    print(mapping)  # output: {'b': 'g'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多