Python - 比较键的值

时间:2017-07-18 21:36:01

标签: python dictionary

假设我们在Python中有以下两个词典:

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4}

dict2 = {'c':2, 'd':1, 'b':2, 'a':1}

现在,我假设dict1中的值是正确的值。如何将dict2dict1进行比较,以便dict2中的键值与dict1中的值类似,程序返回True,并且如果不同,则返回False

感谢。

5 个答案:

答案 0 :(得分:0)

如果你的意思相同,那么你可以直接比较它们:

def compare_dictionaries(correct_dictionary,dictionary_to_check):
    for key,correct_value in correct_dictionary.items():
        if dictionary_to_check[key] != correct_value:
            return False
    return True

如果您缺少要检查的字典中的密钥,上面将抛出KeyError异常,如果您检查的字典包含额外的密钥,则无需处理。

答案 1 :(得分:0)

首次实施

# Both dictionaries can have different keys

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4} # correct dict 
dict2 = {'c':2, 'd':1, 'b':2, 'a':1} # test dict
if all(map(lambda x: dict2.get(x, "dict2") == dict1.get(x, "dict1"), dict2)):
    print "same"
else:
    print "different"

测试用例#1给出“相同”

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4, 'e':5} # correct dict
dict2 = {'c':3, 'd':4, 'b':2, 'a':1} # test dict

测试用例#2给出“不同”

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4 } # correct dict
dict2 = {'c':3, 'd':4, 'b':2, 'a':1, 'e':5} # test dict

第二次实施(与第一次不同,见测试结果)

# Both dictionaries can have different keys

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4} # correct dict 
dict2 = {'c':2, 'd':1, 'b':2, 'a':1} # test dict
if set(dict1.keys()) == set(dict2.keys())  and set(dict1.values()) == set(dict2.values()):
    print "same"
else:
    print "different"

测试用例#1给出“不同”

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4, 'e':5} # correct dict
dict2 = {'c':3, 'd':4, 'b':2, 'a':1} # test dict

测试用例#2给出“不同”

dict1 = {'a':1, 'b':2, 'c':3, 'd': 4 } # correct dict
dict2 = {'c':3, 'd':4, 'b':2, 'a':1, 'e':5} # test dict

答案 2 :(得分:0)

我猜是dict1键:值是所有东西都被比较的东西。

dict2 = {'c':2, 'd':1, 'b':2, 'a':1}

def compareDict(d2):
  dict1 = {'a':1, 'b':2, 'c':3, 'd': 4}

  for key in d2:
    if d2[key] == dict1[key]:
      print("{} key has similar value of {}; It is True".format(key, 
      d2[key]))
    else:
      print("{} key does not have similar value as dict1 key, it has a 
      value of {}; It is False".format(key, d2[key]))

compareDict(dict2)

答案 3 :(得分:0)

首先使用xor操作检查密钥是否相同,然后使用key的相应dictionary检查值。希望这会有所帮助。

dict1 = {'a':2, 'b':2, 'c':3, 'd': 4}
dict2 = {'c':2, 'd':1, 'b':2, 'a':1}
# XOR operator for for checking all key are same.
check_keys= set(dict1.keys()) ^ set(dict2.keys())
keys = set(dict2.keys())
check = False
# a=0 if all key are same.
a = len(check_keys)
# if all key are same than check the value with corresponding key
if not a:
    check = True
    for key in keys:
        if dict1[key] == dict2[key]:
            pass
        else:
            check = False
            break
print(check)

答案 4 :(得分:0)

通过给出布尔标志,按每个键的大小,键和值来比较字典。

->where('students.id', 1)
->where('scores.term_id', 1)
->orWhere('scores.term_id', 2)
->orWhere('scores.term_id', 3)