Check if two dictionaries have same keys in python

I was lazy loading a large json file and wanted to collect only two keys. Running through with ujson I had to check that I had the correct data. I needed to check if my tmp dict was what I wanted. By using set() on a dict you’ll get all the keys and then do the compare easily. Here’s a simplified example of using set() on dictionaries:

key_include = ['artist', 'multiverseId']
outside = ['obc', 'artist']
tmp = ['artist', 'multiverseId']

if set(key_include) == set(outside):
   print('key_include and outside has the same keys')

if set(key_include) == set(tmp):
   print('key_include and tmp has the same keys')

# output key_include and tmp has the same keys
Tagged with: