Reputation: 125
What I am trying to do is to check if a string input is in dictionary, which values are in lists:
data_dict = {'mobile_panel': ["APP", "DTRAFFIC", "DSCHANGE", "SEARCH", "URL", "HTTP", "ALL"],
'socio': ["-20.000 inh", "20.000-50.000 inh", "50.000-100.000 inh", "100.000 inh or more"]}
This is the dictionary. I want to create a functions for every key:value pair:
def mob_panel_in_list(string):
for key, value in data_dict.items():
if string in 'mobile_panel':
return string
else:
return string + '_not_valid'
The next function to be for key - 'socio' and so on. The problem is that this function always returns the else statement. When I change 'mobile_panel' with value, I am getting the correct result, but this works only for the first key:value pair. How can I select the different keys and their values? I am missing something, but can't figure it out.
Upvotes: 0
Views: 85
Reputation: 185
Try this:
def is_string_in_dict(string, data_dict, key):
if string not in data_dict.get(key, []):
return string + '_not_valid'
return string
So you can have, for example:
>>> data_dict = {'mobile_panel': ["APP", "DTRAFFIC", "DSCHANGE", "SEARCH", "URL", "HTTP", "ALL"],
'socio': ["-20.000 inh", "20.000-50.000 inh", "50.000-100.000 inh", "100.000 inh or more"]}
>>> is_string_in_dict('APP', data_dict, 'mobile_panel')
# 'APP' is in 'mobile_panel' list => return 'APP'
APP
>>> is_string_in_dict('APPP', data_dict, 'mobile_panel')
# 'APPP' is not in 'mobile_panel' list => return 'APPP_not_valid'
APPP_not_valid
>>> is_string_in_dict('APP', data_dict, 'socio')
# 'APP' is not in 'socio' list => return 'APPP_not_valid'
APP_not_valid
>>> is_string_in_dict('APP', data_dict, 'missing_key')
# 'missing_key' is not a valid key => return 'APP_not_valid'
APP_not_valid
Upvotes: 0
Reputation: 1747
If you want to make it work for a single key at a time, and the values are always lists, you can do this:
def value_in_dict_list(key, string, mydict):
if string in mydict[key]:
return string
else:
return string + '_not_valid'
value_in_dict_list('mobile_panel', 'APPP', data_dict)
'APPP_not_valid'
If you want to do it for all keys at once and know which ones are which, again assuming values are always lists:
def value_in_dict_list(string, mydict):
out_dict = {}
for k, val in mydict.items():
if string in val:
out_dict[k] = string
else:
out_dict[k] = string + '_not_valid'
return out_dict
value_in_dict_list('APPP', data_dict)
{'socio': 'APPP_not_valid',
'mobile_panel': 'APPP_not_valid'}
Upvotes: 0
Reputation: 1902
Since you want to create separate functions for each key in the dat_dict..
def mob_panel_in_list(panel):
return panel if panel in data_dict['mobile_panel'] else panel+'_not_valid'
Upvotes: 1
Reputation: 144
check this :
def mob_panel_in_list(string):
for key, value in data_dict.items():
if string in key,value:
return string
else:
return string + '_not_valid'
Upvotes: 0