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和dic2具有相同的键,但顺序不同。
如何判断他们有相同的密钥(不考虑订单)?
答案 0 :(得分:27)
python 2.7
<强> dict views 强> 支持直接设置操作等。
>>> 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'])
类似于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:直接将dict键迭代到集合中
>>> dic1 = {'a':'a','b':'c','c':'d'}
>>> dic2 = {'b':'a','a':'c','c':'d'}
>>> set(dic1) == set(dic2)
True
答案 1 :(得分:11)
set(dic1.keys()) == set(dic2.keys())
答案 2 :(得分:1)
我们可以使用所有
all( k in dic2 for k in dic1) and all(k in dic1 for k in dic2)
答案 3 :(得分:0)
我不确定你是如何结束的,keys()
会返回一个未排序的列表,但sorted(dict1.keys()) == sorted(dict2.keys())
应该这样做。