【发布时间】:2015-02-02 20:15:47
【问题描述】:
我正在尝试通过比较键来比较两个字典,如果两个单独字典中的两个键相同,则程序应检查值是否也相同,如果它们不相同,则程序应识别.
这是我写的代码:
def compare(firstdict,seconddict):
shared_items = set(firstdict()) & set(seconddict())
length = len(shared_items)
if length > 0:
return shared_items
if length < 1:
return None
print(compare(firstdict,seconddict))
('firstdict' 和 'seconddict' 是前面函数中制作的两个字典)。
当代码运行时,它会打印出所有相同但没有值的键,即使它们的值不同。
例如,如果:
firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}
seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}
它会打印出来:
'cat', 'blue'
而我正试图让它打印出来:
'cat pet (animal)'
以这种确切的格式。
感谢任何有关如何编辑我的代码的建议 :)
【问题讨论】:
标签: python list dictionary key key-value