问题描述
我想比较两个字典。我的方法是将它们变成两个单独的元组列表,然后使用set模块。这是一个例证:
I'm trying to compare two dictionaries. My approach is to turn them into two separate lists of tuples and to then use the set module. Here is an illustration:
dict = {'red':[1,2,3],'blue':[2,3,4],'green':[3,4,5]}
dict1 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]}
intersection = set(set(dict.items()) & set(dict1.items()))
显然,这是比较两个元组的列表,python不喜欢。我得到一个TypeError:'list'是不可缓解的错误(或类似的措辞)。
apparently, this is comparing two lists of tuples and python doesn't like that. I get a TypeError: 'list' is unhashable error (or similar wording).
我想交集包含 [('green' [3,4,5])]
。任何想法?
I would like intersection to contain [('green',[3,4,5])]
. Any ideas?
推荐答案
shared_keyvals = dict( (key, dict1[key])
for key in (set(dict1) & set(dict2))
if dict1[key] == dict2[key]
)
你甚至可以将它变成一个函数:
You can even make this into a function:
def shared_keyvals(dict1, dict2):
return dict( (key, dict1[key])
for key in (set(dict1) & set(dict2))
if dict1[key] == dict2[key]
)
显然,如果你不喜欢以字典形式输出,你可以删除 dict()
调用并用列表解析括号( []
)。
Obviously, if you prefer to not have the output in dictionary form, you can just remove the dict()
call and replace with with list comprehension brackets ([]
) instead.
这篇关于将两个字典与列表类型值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!