How to find the key name in a dictionary by the value contained in it?

1

Here's an example.

dicio = {'pizza': {'massa', 'ketchup'}, 'feijoada': {'feijão', 'linguiça'}}

user_input = 'feijão', 'linguiça' #Input

How to check if this input is in the values of this list and if it is how can I get the name of the key that has these values and start the user?

    
asked by anonymous 11.11.2017 / 20:42

2 answers

2

Normally what you're doing is the reverse of a traditional mapping.

Now you can turn your multimap into another multimap, this time with inverted keys / values. Here I describe a little better a multimap, so I will not go back much to the formalisms of this definition.

reverse_multimapa = {}
for chave_original, valores in dicio.items():
    for valor in valores:
        try:
            # se chave existir, tudo funciona corretamente
            reverse_multimapa[valor].append(chave_original)
        except KeyError:
            # se chave não existir, vai cair aqui
            reverse_multimapa[valor] = [chave_original]

So, the reverse lookup would just pass the desired value to reverse_multimapa and get its values. Note that in this case, I'm predicting that the case where 'pizza' and 'sanduíche' have as one of the associated values 'ketchup' .

In this case:

print(reverse_multimapa['ketchup'])

Return:

['pizza', 'sanduíche']

An alternative to using pure Python dictionaries is to use the setdefault method in the rescue. This avoids handling the exception (or the None treatment if the get method is used). Tip courtesy of @jsbueno in

11.11.2017 / 21:19
0

A very basic example:

dicio = {'pizza': {'massa', 'ketchup'}, 'feijoada': {'feijão', 'linguiça'}}

def search(term):
    for k, v in dicio.items():
        if term in v:
            return k

    return None

print search('massa')
print search('linguiça')

You just have to adapt the code to get the user input and search.

    
11.11.2017 / 21:06