以下是比较两个字典中一个键所对应的多个值的代码示例:
def compare_values(dict1, dict2, key):
values1 = dict1.get(key, [])
values2 = dict2.get(key, [])
if set(values1) == set(values2):
print(f"The values for key '{key}' are the same.")
else:
print(f"The values for key '{key}' are different.")
# 示例字典
dict1 = {'key1': [1, 2, 3], 'key2': [4, 5, 6]}
dict2 = {'key1': [1, 2, 3], 'key2': [4, 5, 6]}
dict3 = {'key1': [1, 2, 3], 'key2': [7, 8, 9]}
# 比较两个字典中键'key1'对应的值
compare_values(dict1, dict2, 'key1') # 输出: The values for key 'key1' are the same.
compare_values(dict1, dict3, 'key1') # 输出: The values for key 'key1' are different.
在上面的代码示例中,compare_values
函数接受三个参数:两个字典和一个键。函数首先通过get
方法从字典中获取键所对应的值,如果键不存在则返回一个空列表[]
。然后,将两个字典中键所对应的值转换为集合,并使用set
函数进行比较。如果两个集合相等,则表示两个字典中该键对应的值是相同的;否则,表示值不相同。根据比较结果输出相应的提示信息。
上一篇:比较两个字典中列表中的日期