【问题标题】:Compare two dictionaries, remove key/value pair in one dict if it exists in the other比较两个字典,如果它存在于另一个字典中,则删除一个字典中的键/值对
【发布时间】:2017-07-06 08:07:24
【问题描述】:

我有两本字典。一个看起来像这样:

dict1 = {'ana': 'http://ted.com', 'louise': 'http://reddit.com', 'sarah':'http://time.com'}

另一个看起来像这样:

dict2 = {'patricia': 'http://yahoo.com', 'ana': 'http://ted.com',
         'louise': 'http://reddit.com', 'florence': 'http://white.com'}

我需要比较这两个字典,并从dict2 中删除任何已存在于dict1 中的键/值对

如您所见,dict1 中已经存在 Ana 和 Louise,所以我想自动将其从 dict2 中删除 预期的输出将包含 onlydict2 唯一的元素并且dict1 中尚不存在,并且看起来像:

dict2 = {'patricia': 'http://yahoo.com', 'florence': 'http://white.com'}

我不需要对 Sarah 加入 dict1 做任何事情。我只关心比较 dict2dict1 以删除重复项。

额外信息:

我尝试以多种不同的方式遍历字典,但它给了我两种类型的错误:not hashable typedict content changed during action

我也试过把每一个都做成一个列表,然后合并列表,但最终结果是另一个列表,我不知道如何把一个列表重新变成字典。

【问题讨论】:

  • 你关心键和值是否相等,还是只关心键?

标签: python python-3.x dictionary duplicates


【解决方案1】:

Jim's answer 如果键匹配,则删除项目。如果键 值都匹配,我认为您想删除。这实际上非常简单,因为您使用的是 Python 3:

>>> dict(dict2.items() - dict1.items())
{'florence': 'http://white.com', 'patricia': 'http://yahoo.com'}

之所以有效,是因为dict_items 对象将减法运算视为集合差异。

【讨论】:

  • 如此简洁和优雅。哇。非常感谢大家
【解决方案2】:

如果你们中的任何人正在寻找 python 2.x 的解决方案(因为我一直在寻找),那么这里就是答案:

dict(filter(lambda x: x not in dict2.items(), dict1.items()))

【讨论】:

    【解决方案3】:

    然后只需使用字典理解:

    dict2 = {i:j for i,j in dict2.items() if i not in dict1}
    

    这导致dict2 成为:

    {'florence': 'http://white.com', 'patricia': 'http://yahoo.com'}
    

    就地解决方案可能是:

    for k in dict1:
        dict2.pop(k, None)
    

    产生类似的结果。

    【讨论】:

      【解决方案4】:

      这只是在 dict1 中查找 dict2 中的所有键,然后从 dict2 中删除键/值对。

      for key in dict1:
          if key in dict2 and (dict1[key] == dict2[key]):
              del dict2[key]
      

      这有帮助!

      【讨论】:

        猜你喜欢
        • 2021-09-03
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多