【问题标题】:Comparing two dictionaries in Python by identifying sets with same key but different values通过识别具有相同键但不同值的集合来比较 Python 中的两个字典
【发布时间】:2015-02-02 20:15:47
【问题描述】:

我正在尝试通过比较键来比较两个字典,如果两个单独字典中的两个键相同,则程序应检查值是否也相同,如果它们不相同,则程序应识别.

这是我写的代码:

def compare(firstdict,seconddict):
    shared_items = set(firstdict()) & set(seconddict())
    length = len(shared_items)
    if length > 0:
        return shared_items
    if length < 1:
        return None
print(compare(firstdict,seconddict))

('firstdict' 和 'seconddict' 是前面函数中制作的两个字典)。

当代码运行时,它会打印出所有相同但没有值的键,即使它们的值不同。

例如,如果:

firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}

seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}   

它会打印出来:

'cat', 'blue'

而我正试图让它打印出来:

'cat pet (animal)'

以这种确切的格式。

感谢任何有关如何编辑我的代码的建议 :)

【问题讨论】:

    标签: python list dictionary key key-value


    【解决方案1】:

    您可以在字典keys() 上使用集合交集。然后遍历这些并检查与这些键对应的值是否相同。如果没有,您可以使用format 打印出来。

    def compare(first, second):
        sharedKeys = set(first.keys()).intersection(second.keys())
        for key in sharedKeys:
            if first[key] != second[key]:
                print('Key: {}, Value 1: {}, Value 2: {}'.format(key, first[key], second[key]))
    
    >>> compare(firstdict, seconddict)
    Key: cat, Value 1: animal, Value 2: pet
    

    再举一个例子

    >>> firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star', 'name': 'bob', 'shape': 'circle'}
    >>> seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star', 'name': 'steve', 'shape': 'square'}
    
    >>> compare(firstdict, seconddict)
    Key: shape, Value 1: circle, Value 2: square
    Key: cat, Value 1: animal, Value 2: pet
    Key: name, Value 1: bob, Value 2: steve
    

    【讨论】:

      【解决方案2】:

      如果您的值是可散列的,您也可以使用项目来获取通用键/值对:

      firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}
      
      seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}
      
      common = set(firstdict.iteritems()).intersection(seconddict.iteritems())
      
      for k,v in common:
          print("Key: {}, Value: {}".format(k,v))
      Key: blue, Value: colour
      

      要检查两个字典是否相同,请检查每个字典的 len:

      print(len(common)) == len(firstdict)
      

      查找具有不同值的公共键:

      for k,v in firstdict.iteritems():
          if k in seconddict and seconddict[k] != v:
              print("Key: {}, Value: {}".format(k, seconddict[k]))
      Key: cat, Value: pet
      

      【讨论】:

        【解决方案3】:

        在您的示例代码中使用集合使其效率低于简单地循环键,这也可能更具可读性:

        firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}
        seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}
        
        def compare(firstdict, seconddict):
            for key in firstdict:
                if key in seconddict:
                    first, second = firstdict[key], seconddict[key]
                    if first != second:
                        print('%s %s (%s)' % (key, first, second))
        
        compare(firstdict, seconddict)
        

        输出:

        cat animal (pet)
        

        【讨论】:

          【解决方案4】:

          Padraic 的方法似乎比这个更好,但它是另一种选择。所以这不是最好的方法,但它可以完成工作。

          逐步检查每个元素并手动比较它们。

          def compare(dictOne,dictTwo):
              for keyOne in dictOne:
                  for keyTwo in dictTwo:
                      if keyTwo == keyOne:
                          if dictOne[keyOne] != dictTwo[keyTwo]:
                              print(keyOne+" "+dictOne[keyOne]+" ("+dictTwo[keyTwo]+")")
          
          compare(firstdict,seconddict)
          

          您的问题是假设要打印出来,并没有提到您希望它们以数组的形式返回,因此上面的代码将逐个比较两个字典,并以不匹配的格式打印出来。

          【讨论】:

          • ekhumoro 的响应可能会更节省资源。
          猜你喜欢
          • 2022-11-29
          • 2022-01-18
          • 2021-12-15
          • 2014-12-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-20
          • 2020-12-18
          相关资源
          最近更新 更多