Python – Check for the presence of a value in the corresponding list

Check for the presence of a value in the corresponding list… here is a solution to the problem.

Check for the presence of a value in the corresponding list

I’m trying to create a for loop that dynamically checks for the presence of a value in the corresponding list. I don’t know exactly if I can convert strings in the list, or if there’s a better way to do this.

rating_1 = ['no', 'yes']
rating_2 = ['no', 'yes']

for item in d:
    if d[item] not in item: # I don't want to use the item,
                            # only get name that will match the respective list above
        print "value not allowed"

d =  {'rating_2': u'no', 'rating_1': u'no'}

Solution

my_lists = {
'rating_1' = ['no', 'yes'],
'rating_2' = ['no', 'yes'],
}

d =  {'rating_2': u'no', 'rating_1': u'no'}

for item in d:
    if d[item] not in my_list[item]:
        print "value not allowed"

Or, if you want to use variables, use vars() to provide a dictionary of the current namespace, where you can use variable names as keys.

rating_1 = ['no', 'yes']
rating_2 = ['no', 'yes']

d =  {'rating_2': u'no', 'rating_1': u'no'}

for item in d:
    if d[item] not in vars()[item]:
        print "value not allowed"

Related Problems and Solutions