0

I have two lists:

  • Keys that must be in dict
  • Keys that are optional for dict

    1. how can I check if the keys that must be there in a dictionary are there or not?
    2. how can I check if any of the optional keys is there in the dictionary or not?
IcyFlame
  • 5,059
  • 21
  • 50
  • 74
Plastic Rabbit
  • 2,859
  • 4
  • 25
  • 27

2 Answers2

5

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • It's also worth noting that in Py3k `dict.keys()` works like `dict.viewkeys()` which no longer exists – jamylak May 13 '13 at 08:43
  • The first line, the subtraction, looks backwards. Wouldn't you want to subtract/remove "required" from the dict? Meaning: `missing = some_dict.view() - set(required)` (Python3 syntax) – ahogen Jun 05 '18 at 16:58
  • @ahogen: no, because then you get the keys that are *extra*, over and on top of the required keys. You want all keys that are in the `required` set, but which are not in the dictionary, which is what the expression in my answer achieves. – Martijn Pieters Jun 05 '18 at 17:34
1

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) 
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504