开发者

Python: How to know if two dictionary have the same keys

dic1 = {'a':'a','b':'c','c':'d'}
dic2 = {'b':'a','a':'c','c':'d'}

dic1.keys()    =>['a', 'b', 'c']
dic2.keys()    =>['b', 'a', 'c']

dic1 and dic2 have the same keys, but in different o开发者_StackOverflowrder.

How to tell they have same keys(do not consider the order)?


python 2.7

dict views: Supports direct set operations, etc.

>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> dic1.viewkeys() == dic2.viewkeys()
True
>>> dic1.viewkeys() - dic2.viewkeys()
set([])
>>> dic1.viewkeys() | dic2.viewkeys()
set(['a', 'c', 'b'])

similarly in 3.x: (thx @lennart)

>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> dic1.keys() == dic2.keys()
True
>>> dic1.keys() - dic2
set()
>>> dic1.keys() | dic2
{'a', 'c', 'b'}

python 2.4+

set operation: direct iteration over dict keys into a set

>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> set(dic1) == set(dic2)
True


set(dic1.keys()) == set(dic2.keys())


We can use all

all( k in dic2 for k in dic1) and all(k in dic1 for k in dic2)


I am not sure how you ended making keys() return you an unsorted list but sorted(dict1.keys()) == sorted(dict2.keys()) should do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜