Reputation: 2999
I have two lists:
Keys that are optional for dict
Upvotes: 0
Views: 312
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
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