Python3 Determine if two dictionaries are equal [duplicate]

风流意气都作罢 提交于 2019-12-10 03:34:25

问题


This seems trivial, but I cannot find a built-in or simple way to determine if two dictionaries are equal.

what I want is:

a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
b = {'foo': 2, 'bar': 1}
e = {'foo': 1, 'bar': 2, 'baz':3}
f = {'foo': 1}


equal(a, b)   # True 
equal(a, c)   # True - order does not matter
equal(a, d)   # False - values do not match
equal(a, e)   # False - e has additional elements
equal(a, f)   # False - a has additioonal elements

I could make a short looping script, but I cannot imagine that mine is such a unique usecase


回答1:


== works

a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
True

I hope the above example helps you.




回答2:


The good old == statement works.




回答3:


a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
d = {'foo': 2, 'bar': 1}
e = {'foo': 1, 'bar': 2, 'baz':3}
f = {'foo': 1}

print(a.items() == b.items())
print(a.items() == c.items())
print(a.items() == d.items())
print(a.items() == e.items())
print(a.items() == f.items())

Output

True
True
False
False
False


来源:https://stackoverflow.com/questions/53348959/python3-determine-if-two-dictionaries-are-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!