filmov
tv
Check if Dictionary Has Mandatory keys - Real Life Programming | Python Bits | Kovolff
![preview_player](https://i.ytimg.com/vi/PdJgnlF6KOg/sddefault.jpg)
Показать описание
How to check whether a structure like a Python dictionary has the minimum required keys.
Additionally these keys can come in multiple variants. How do you go about such a problem?
Here's one way of tackling this challenge:
Step 1:
Create a tuple of tuples, i.e.
mandatory_parameters = (('username', 'user_name', 'user'), ('user_password', 'password'), ('mail', 'e-mail', 'email'))
each element is the main tuple is basically a tuple, representing a term in its different variants
Step 2:
Create a empty list and a status variable, the latter initialized to 0
i.e. elements_status = []
dict_status = 0
Step 3
Loop through the mandatory_parameters tuple and see if any of the variants are in your dictionary. If so, then append an item to your elements_status list
i.e.
for i in range(len(mandatory_list)):
for j in range(len(mandatory_list[i])):
if mandatory_list[i][j] in dict_to_check:
break
The thing is that if our dictionary fulfills the requirements, the elements_status list should be of equal length to the mandatory_parameters tuple
hence we carry out the following checks:
i.e.
if len(elements_status) == len(mandatory_list):
dict_status = 1
else:
dict_status = 0
Dict_status = 1 signifies that our dictionary fulfills the mandatory requirements.
#python #dictionary #keys
Additionally these keys can come in multiple variants. How do you go about such a problem?
Here's one way of tackling this challenge:
Step 1:
Create a tuple of tuples, i.e.
mandatory_parameters = (('username', 'user_name', 'user'), ('user_password', 'password'), ('mail', 'e-mail', 'email'))
each element is the main tuple is basically a tuple, representing a term in its different variants
Step 2:
Create a empty list and a status variable, the latter initialized to 0
i.e. elements_status = []
dict_status = 0
Step 3
Loop through the mandatory_parameters tuple and see if any of the variants are in your dictionary. If so, then append an item to your elements_status list
i.e.
for i in range(len(mandatory_list)):
for j in range(len(mandatory_list[i])):
if mandatory_list[i][j] in dict_to_check:
break
The thing is that if our dictionary fulfills the requirements, the elements_status list should be of equal length to the mandatory_parameters tuple
hence we carry out the following checks:
i.e.
if len(elements_status) == len(mandatory_list):
dict_status = 1
else:
dict_status = 0
Dict_status = 1 signifies that our dictionary fulfills the mandatory requirements.
#python #dictionary #keys