0

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

7
  • 2
    itemgetter(*findvalues)(lst) if I understood you right. Commented Jul 22, 2022 at 6:10
  • Get their values or indexes? Commented Jul 22, 2022 at 6:12
  • Did you mean these to be dictionaries or lists? Right now you have two dictionaries, and the findvalues dictionary is invalid. Commented Jul 22, 2022 at 6:18
  • 1
    @ASimpleProgrammer findvalues is a valid set Commented Jul 22, 2022 at 6:21
  • 1
    @ASimpleProgrammer the top one is a set and not a dict Commented Jul 22, 2022 at 6:21

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Typo - ... what you want to achieve? The List Comp. can be simplified to - ``` [myDict[key] for key in findvalues if key in myDict]```
Better answer would be @OlvinRoght's. But it will need import operator.
@DanielHao thanks. The itemgetter is indeed shorter, maybe even faster, but as this is a beginner question I prefere solutions which teach the core concepts of python.
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.