如何比较字典和 Python 中的函数 3+

How to compare dictionaries with a function in Python 3+

我想将字典与函数内的精确模式进行比较。 我的最终目标是:

例如:

dict1 = {"EX1": "C", "EX2": "D", "EX4": "A", "EX5": "A"}
dict2 = {"EX1": "C", "EX2": "A", "EX3": "A", "EX4": "A", "EX5": "A"}

预期输出:

8

8 因为: -EX1 键在两个字典中具有相同的值(3)

-EX2键在两个字典中的值不同(3-1=2)

-EX3 key 不存在于 dict1 中所以没有操作(2)

-EX4键在两个字典中的值相同(2+3=5)

-EX5键在两个字典中的值相同(5+3=8)

我从互联网上得到了这两个我不知道如何转换成函数的片段我不知道这些是否有帮助:

{k : dict1[k] for k in dict1 if k in rep_valid and dict1[k] == rep_valid[k]} #Get same items
{k : dict2[k] for k in set(dict2) - set(dict1)} #Get difference

您可以使用列表理解来获得答案:

dict1 = {"EX1": "C", "EX2": "D", "EX4": "A", "EX5": "A"}
dict2 = {"EX1": "C", "EX2": "A", "EX3": "A", "EX4": "A", "EX5": "A"}

# (count matching keys)*3 - (count not matching keys)
ttl = len([k for k in dict1 if k in dict2 and dict1[k]==dict2[k]]) * 3 - len([k for k in dict1 if k in dict2 and dict1[k]!=dict2[k]])

print(ttl)  # 8
count = 0
for key in (set(dict1.keys()) & set(dict2.keys())):
    if dict1.get(key) == dict2.get(key):
        count += 3
    else:
        count -= 1
print(f"count = {count}")

#count = 8

您可以使用以下函数,它也支持嵌套字典:

def is_dict_equal(d1, d2):
    # for each key in d1
    for key in d1.keys():
        # check if d2 also has the key
        if key not in d2:
            return False

        value1 = d1.get[key]
        value2 = d2.get[key]
        if isinstance(value1, dict): # if the value is another dictionary call this function again
            if not is_dict_equal(value1, value2):
                return False
        elif value1 != value2: # else just compare them with eachother
            return False

    # check for keys in d2 but not in d1
    for key in d2.keys():
        if key not in d1:
            return False

    return True