✓ @anvd, as I understood from your problem, you want to search the presence of values of dictionary d inside the lists rating1 & rating2.
Please comment, if I'm wrong or the solution that I provided below doesn't satisfy your need.
I will suggest you to create 1 more dictionary d_lists that maps the name of lists to the original list objects.
Steps:
✓ Take each key(list name) from d.
✓ Find the existence of this key in the d_lists.
✓ Take the corresponding list object from d_lists.
✓ Find the existence of value pointed by key in d inside picked list object.
✓ If element found then stop iteration and search the presence of next value in d.
✓ Print relevant messages.
Here is your modified code (with little modification)
I have shown another good example later after the below code example.
rating_1 = ['nlo', 'yes']
rating_2 = ['no', 'yes']
# Creating a dictionary that maps list names to themselves (original list object)
d_lists = {
"rating_1": rating_1,
"rating_2": rating_2,
}
# Creating a dictionary that maps list to the item to be searched
# We just want to check whether 'rating_1' & 'rating_2' contains 'no' or not
d = {'rating_2': u'no', 'rating_1': u'no'}
# Search operation using loop
for list_name in d:
if list_name in d_lists:
found = False
for item in d_lists[list_name]:
if item == d[list_name]:
found = True
break
if found:
print "'" + d[list_name] + "' exists in", d_lists[list_name];
else:
print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name]
else:
print "Couldn't find", list_name
Output:
'no' exists in ['no', 'yes']
'no' doesn't exist in ['nlo', 'yes']
Now, have a look at another example.
Another big example:
rating_1 = ['no', 'yes', 'good', 'best']
rating_2 = ['no', 'yes', 'better', 'worst', 'bad']
fruits = ["apple", "mango", "pineapple"]
# Creating a dictionary that maps list names to themselves (original list object)
d_lists = {
"rating_1": rating_1,
"rating_2": rating_2,
"fruits": fruits,
}
# Creating a dictionary that maps list to the item to be searched
# We just want to check whether 'rating_1' & 'rating_2' contains 'no' or not
d = {'rating_2': u'best', 'rating_1': u'good', 'fruits2': "blackberry"}
# Search operation using loop
for list_name in d:
if list_name in d_lists:
print "Found list referred by key/name", list_name, "=", d_lists[list_name];
found = False
for item in d_lists[list_name]:
if d[list_name] == item:
found = True
break
if found:
print "'" + d[list_name] + "' exists in", d_lists[list_name], "\n";
else:
print "'" + d[list_name] + "' doesn't exist in", d_lists[list_name], "\n"
else:
print "Couldn't find list referred by key/name ", list_name, "\n"
Output:
Found list referred by key/name rating_2 = ['no', 'yes', 'better', 'worst', 'bad']
'best' doesn't exist in ['no', 'yes', 'better', 'worst', 'bad']
Couldn't find list referred by key/name fruits2
Found list referred by key/name rating_1 = ['no', 'yes', 'good', 'best']
'good' exists in ['no', 'yes', 'good', 'best']