Me All
Me All

Reputation: 269

Dictionaries with lists as values: how to retrieve the key given one value

I have a Python dictionary which looks like this:

alphabetic_dict = {
'a':['apple', 'ant', 'atlas'],
'b':['bee', 'beer','bat'],
'c':['car', 'cash', 'computer']
}

What I want to do is, given one of the values within a list, print the corresponding key. For example, if I write car, I want my program to output something like That value corresponds to 'c'. It might seem a silly thing, but I've never worked with a dictionary containing lists as values, so I'm very confused.

Upvotes: 0

Views: 23

Answers (2)

Paymahn Moghadasian
Paymahn Moghadasian

Reputation: 10329

input = 'c'
for key, values in alphabetic_dict.items():
    if input in values:
        print(f'That value corresponds to {key}')

This uses f-strings which were introduced in python 3.6

Upvotes: 0

rdas
rdas

Reputation: 21275

Search the value (which is a list) for the thing you;re looking for

for k, v in alphabetic_dict.items()
    if 'car' in v:
       print k

Upvotes: 1

Related Questions