Say I have a dictionary with keys being a category name and values being words within that category. For example:
words={
'seasons':('summer','spring','autumn','winter'),
'rooms':('kitchen','loo','livingroom','hall','diningroom','bedroom'),
'insects':('bee','butterfly','beetle')}
For any given input I want to create a list with two items where the first item is the value word and the second is the key word. For example, the expected output should be:
input: kitchen
output: ['kitchen','rooms']
input: bee
output: ['bee','insects']
I checked the question Get key by value in dictionary but afaict all answers work for dictionaries with 1 value per key.
I've tried the following naive, closed form code:
word=input('Enter a word: ')
word_pair=[]
word_pair.append(word)
if word in (words['seasons']):
index=0
elif word in (words['rooms']):
index=1
elif word in (words['insects']):
index=2
else:
index=3
try:
key_val=list(words.keys())[index]
word_pair.append(key_val)
except IndexError:
word_pair.append('NA')
print(word_pair)
Obviously, this code only works for this specific dictionary as is. If I wanted to add a category, I'd have to add an elif clause. If I wanted to change the name of a category or their order, remove one, combine two or more, etc., I'd have to tweak a whole bunch of things by hand.
Is there a more generalized way to do this?
All help is appreciated.