我有两本字典,但为了简化起见,我就选这两本:
>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)
现在,我想比较x中的每个键值对在y中是否有相同的对应值,所以我这样写:
>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
if x_values == y_values:
print 'Ok', x_values, y_values
else:
print 'Not', x_values, y_values
它的工作原理是返回一个元组,然后比较是否相等。
我的问题:
这对吗?还有更好的办法吗?最好不是在速度上,我说的是代码优雅。
更新:我忘了提到,我必须检查有多少键,值对是相等的。
@mouad的答案很好,如果你假设两个字典都只包含简单的值。然而,如果你有包含字典的字典,你会得到一个异常,因为字典是不可哈希的。
在我的脑海中,这样做可能有用:
def compare_dictionaries(dict1, dict2):
if dict1 is None or dict2 is None:
print('Nones')
return False
if (not isinstance(dict1, dict)) or (not isinstance(dict2, dict)):
print('Not dict')
return False
shared_keys = set(dict1.keys()) & set(dict2.keys())
if not ( len(shared_keys) == len(dict1.keys()) and len(shared_keys) == len(dict2.keys())):
print('Not all keys are shared')
return False
dicts_are_equal = True
for key in dict1.keys():
if isinstance(dict1[key], dict) or isinstance(dict2[key], dict):
dicts_are_equal = dicts_are_equal and compare_dictionaries(dict1[key], dict2[key])
else:
dicts_are_equal = dicts_are_equal and all(atleast_1d(dict1[key] == dict2[key]))
return dicts_are_equal
dic1 == dic2
来自python文档:
下面的例子都返回一个字典等于
{" 1 ": 1, " 2 ": 2, " 3 ": 3}:
>>> a = dict(1 =1, 2 =2, 3 =3)
>>> b = {' 1 ': 1, ' 2 ': 2, ' 3 ': 3}
> > > c = dict (zip([“一”,“两个”,“三”],[1,2,3]))
> > > d = dict([(2, 2),('一',1),(‘三’,3)))
>>> e = dict({'三':3,'一':1,'二':2})
a == b == c == d == e
真正的
在第一个例子中提供关键字参数只适用于
是有效的Python标识符的键。否则,任何有效的密钥都可以
被使用。
适用于python2和python3。
你可以用下面的方法写出你自己的函数。
class Solution:
def find_if_dict_equal(self,dict1,dict2):
dict1_keys=list(dict1.keys())
dict2_keys=list(dict2.keys())
if len(dict1_keys)!=len(dict2_keys):
return False
for i in dict1_keys:
if i not in dict2 or dict2[i]!=dict1[i]:
return False
return True
def findAnagrams(self, s, p):
if len(s)<len(p):
return []
p_dict={}
for i in p:
if i not in p_dict:
p_dict[i]=0
p_dict[i]+=1
s_dict={}
final_list=[]
for i in s[:len(p)]:
if i not in s_dict:
s_dict[i]=0
s_dict[i]+=1
if self.find_if_dict_equal(s_dict,p_dict):
final_list.append(0)
for i in range(len(p),len(s)):
element_to_add=s[i]
element_to_remove=s[i-len(p)]
if element_to_add not in s_dict:
s_dict[element_to_add]=0
s_dict[element_to_add]+=1
s_dict[element_to_remove]-=1
if s_dict[element_to_remove]==0:
del s_dict[element_to_remove]
if self.find_if_dict_equal(s_dict,p_dict):
final_list.append(i-len(p)+1)
return final_list
你要做的就是x==y
你这样做不是一个好主意,因为字典里的条目不应该有任何顺序。你可能会比较[('a',1),('b',1)]和[('b',1), ('a',1)](相同的字典,不同的顺序)。
例如,看这个:
>>> x = dict(a=2, b=2,c=3, d=4)
>>> x
{'a': 2, 'c': 3, 'b': 2, 'd': 4}
>>> y = dict(b=2,c=3, d=4)
>>> y
{'c': 3, 'b': 2, 'd': 4}
>>> zip(x.iteritems(), y.iteritems())
[(('a', 2), ('c', 3)), (('c', 3), ('b', 2)), (('b', 2), ('d', 4))]
虽然只有一项不同,但你的算法会发现所有项都是不同的