Home > Back-end >  python - multiple value search in list and get values or indexes
python - multiple value search in list and get values or indexes

Time:07-22

How can i get multiple values indexes in a list

findvalues = {'1','2'}
list = {'1':{'A'},'2':{'B'},'3':{'C'},'4':{'D'}}

I need to search findvalues in list and get their values or indexes

CodePudding user response:

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 archive. Something like this might do what you want:

filteredDict = [myDict[key] for key in findvalues if key in myDict.keys() ]

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.keys()

CodePudding user response:

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

list=[1,2,3,4,5,6,7,8,9]
def find_values(a,b):
    loc3=[]
    for i in range (len(list)):
        if a==list[i]:
            loc1=i
        if b==list[i]:
            loc2=i
    loc3.append(loc1)
    loc3.append(loc2)
    return loc3
print(find_values(2,7))
  • Related