Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 order.

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

like image 652
user469652 Avatar asked Jan 11 '11 09:01

user469652


1 Answers

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
like image 112
kevpie Avatar answered Oct 20 '22 12:10

kevpie