Plastic Rabbit
Plastic Rabbit

Reputation: 2999

How to check if dictionary has unwanted keys?

I have two lists:

Upvotes: 0

Views: 312

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124110

Use dictionary views and sets:

missing = set(required) - some_dict.viewkeys()
optional_present = some_dict.viewkeys() & optional

Sets, like dictionaries, make membership testing cheap and fast, and set operations make it easy to test if items are present or not. You really want to make required and optional be sets to starts with.

For example, subtraction on sets calculates the difference, so missing is set to the difference between the required list and what keys are in the dictionary.

Using the & operator on sets (normally binary AND) gives you the intersection, so optional_present gives you what keys in the dictionary are also in the optional sequence (doesn't have to be a set in this case, but using a set there would make sense).

For testing individual keys you can still use key in some_dict, but using set operations avoids excessive looping.

Note that dict.viewkeys() is specific to Python (added in Python 2.7); in Python 3, the dictionary enumeration methods .keys(), .values() and .items() return dictionary views by default and the .view*() methods are gone.

Upvotes: 5

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251116

You can use the key in your_dict for the first case and set difference will solve the second one. Dicts can behave like sets using dict.viewkeys() (dict.keys() in py3x):

You can use all() to check if all the keys in a list are present in a dict.

all(key in your_dict for key in keys)

Set difference:

your_dict.viewkeys() - set(keys) 

Upvotes: 1

Related Questions