如何比较两个不同键的字典,例如下面的字典?
dictionary={"name":"abc","age":23,"male":True}
new_dictionary={"my_name":"abc","my_age":23,"male":1}
当比较示例中的两个字典时,比较应该返回true
。
如何比较两个不同键的字典,例如下面的字典?
dictionary={"name":"abc","age":23,"male":True}
new_dictionary={"my_name":"abc","my_age":23,"male":1}
当比较示例中的两个字典时,比较应该返回true
。
>>> 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
)
您需要定义比较发生的确切方式。如果您只想比较这些值,无论它们分配给什么键,都可以使用:
根据您的更新要求,其中一种解决方案是:
>>> 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
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