Reputation: 27
How can i search for multiple values in dictionary to other dictionary ?
findvalues = {'1','2'}
listvalues = {'1':{'A'},'2':{'B'},'3':{'C'},'4':{'D'}}
I need to search findvalues in listvalues and get their values or indexes
Upvotes: 0
Views: 110
Reputation: 28
i made some code that does what the question asks but it is very inflexible, it cant work if there is not the item you are looking for and if you want to search for more than two items it wont work. remember that lists start at 0 not 1
mylist=[1,2,3,4,5,6,7,8,9]
def find_values(a,b):
loc3=[]
for i in range (len(mylist)):
if a==mylist[i]:
loc1=i
if b==mylist[i]:
loc2=i
loc3.append(loc1)
loc3.append(loc2)
return loc3
print(find_values(2,7))
Upvotes: 0
Reputation: 2273
Your dictionary is called list
. But this is a build-in name. Never use those. Here is a list of build-ins
Addionally, are you sure you want to have the items in the dict
in an extra set? If not, you can just define them as strings:
myDict = {'1':'A','2':'B','3':'C','4':'D'}
I am not completly sure what you want to achieve. Something like this might do what you want:
filteredDict = [myDict[key] for key in findvalues if key in myDict ]
It creates a list
of items which are the values stored at the keys in your findvalues
set. Additionally it filters out keys that are not inside the list. If you want it rather to throw an exception if that happens, just leave out the if key in myDict
To also have the suggested solution from @OlvinRoght's comment in an answer, I'll add this here.
The itemgetter is part of the operator lib, which you will need to import.
from operator import itemgetter
filteredDict = itemgetter(*findvalues)(myDict)
Upvotes: 2