python - How to check if dictionary has unwanted keys? -


i have 2 lists:

  • keys must in dict
  • keys optional dict

    1. how can check if keys must there in dictionary there or not?
    2. how can check if of optional keys there in dictionary or not?

use dictionary views , sets:

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

sets, dictionaries, make membership testing cheap , fast, , set operations make easy test if items present or not. want make required , optional sets starts with.

for example, subtraction on sets calculates difference, missing set difference between required list , keys in dictionary.

using & operator on sets (normally binary and) gives intersection, optional_present gives keys in dictionary in optional sequence (doesn't have set in case, using set there make sense).

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

note dict.viewkeys() specific python (added in python 2.7); in python 3, dictionary enumeration methods .keys(), .values() , .items() return dictionary views default , .view*() methods gone.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -