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