How to retrieve the target value key for a target value that is contained within a dictionary of lists of values without using a for loop?

Viewed 58

I have the following dictionary. Each key contains a list of unique values:

d = {1:[10,11,12],2:[13,14],3:[15,16,17,18],4:[19],5:[20]}

I want to return the key for specified target value as per the example below (this does return the desired result).

keys = list(d.keys())

values_lst = list(d.values())

target_value = 20

for i,values in enumerate(values_lst):
    if target_value in values:
        index = i

keys[index]

5

However, is there a way to achieve this result without deploying the for loop (at least explicitly). The solution that I have does not feel particularly pythonic.

Thanks!

2 Answers

There always must be a loop somewhere, but you can do it with an one-liner:

d = {1: [10, 11, 12], 2: [13, 14], 3: [15, 16, 17, 18], 4: [19], 5: [20]}

target_value = 20

key = next(k for k, v in d.items() if target_value in v)
print(key)

Prints:

5

A more Pythonic solution, but still with an explicit for:

index = -1
for key, values in d.items():
    if target_value in values:
        index = key
        break
print(d[index])

This may be more readable than a one-liner (as in the other answer), but YMMV.

Related