0

So this is related to a shorter question posted here earlier: Get key by value in dictionary

I adapted the example that the values be lists of int. Say I had this,

mydict = {'george':[1,2,3],'amber':[18,19]}

then I could output "amber" by:

print(list(mydict.keys())[list(mydict.values()).index([18,19])])

Is there a way to adjust this so I can output "amber" by "asking" for just one item of the list? i.e. e.g. 19?

Summary: I want to ask my dictionary: "Give me the key that has in its value(list) the item "19"

Community
  • 1
  • 1
sibert
  • 427
  • 2
  • 5
  • 10
  • 2
    if you have to do this often, you have a design problem. You're really supposed to go the *other* way, from `key` -> `value` – Ian McLaird Nov 23 '15 at 14:01
  • Yes, I am aware of that. The data structure at hand requires me this time to try it the other way round. Thanks anyway =) – sibert Nov 23 '15 at 14:52

3 Answers3

8

Use a list comprehension with a conditional

>>> mydict = {'george':[1,2,3],'amber':[18,19]}
>>> [i for i in mydict if 19 in mydict[i]]
['amber']

Here you get a list of all the keys that has in its value a list with the item 19.

If you want only the first element you can use [i for i in mydict if 19 in mydict[i]][0]

Another innovative way would be using filter

>>> filter(lambda x: 19 in x[1], mydict.items())
[('amber', [18, 19])]

Note that here you get both the key and value as a pair.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

Adapting the answer from the question you linked:

for name, l in mydict.iteritems():
    if 19 in l:
        print name
Ian McLaird
  • 5,507
  • 2
  • 22
  • 31
0

Assuming you want to search many times, building a lookup to index directly will be faster:

mydict = {'george':[1,2,3],'amber':[18,19]}
lookup = dict((number, name) for name, numbers in mydict.items() for number in numbers)
print lookup[19]

A drawback is this index needs to be rebuilt or updated if mydict changes.

jozxyqk
  • 16,424
  • 12
  • 91
  • 180