比较python中不同键的两个词典

时间:2012-06-19 16:31:24

标签: python

如何比较不同键的两个词典,例如下面的词典?

dictionary={"name":"abc","age":23,"male":True}
new_dictionary={"my_name":"abc","my_age":23,"male":1}

比较示例中的两个词典时,比较应返回true

3 个答案:

答案 0 :(得分:2)

>>> dictionary={"name":"abc","age":23,"male":True}
>>> new_dictionary={"my_name":"abc","my_age":23,"male":1}
>>> key_map = {"name": "my_name", "age": "my_age"}
>>> all(new_dictionary[key_map.get(k, k)] == v for k, v in dictionary.items())
True

或者,如果您只是想确保在没有任何密钥检查的情况下值相同的话:

>>> set(dictionary.values()) == set(new_dictionary.values())
True

编辑:正如Tadeck在评论中指出的那样,sorted()set()更安全。

(是的,即使一个词典有1而另一个词典有True

答案 1 :(得分:2)

您需要定义比较发生的确切方式。如果您只想比较这些值,无论它们被分配给哪些键,您都可以使用:

按值比较(忽略键)

根据您的更新要求,其中一个解决方案是:

>>> def compare(dict1, dict2):
    return sorted(dict1.values()) == sorted(dict2.values())

>>> compare({"name":"abc","age":23,"male":True},
    {"my_name":"abc","my_age":23,"male":1})
True
>>> compare({"name":"abc","age":23,"male":True},
    {"my_name":"abc","my_age":24,"male":1})
False

答案 2 :(得分:1)

dictionary={"name":"abc","age":23,"male":True}
new_dictionary={"my_name":"abc","my_age":23,"male":1}    
dict_alias = {"name":"my_name","age":"my_age","male":"male"}

def compare(dictionary,new_dictionary,dict_alias):
    same = True
    for key in dictionary.keys():
        if dictionary[key] == new_dictionary[dict_alias[key]]:
            continue
        else:
            same = False
            break
    return same