Marko
Marko

Reputation: 21

Filter values of a dictionary of lists, and return key

Take this for example:

d = {1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'], 3: [1, 'i', 'j']}

I want to check if a value x exists inside of any of the lists in the dictionary, if it does, return the key of the list it's in.

So checking if 1 was in any of the lists in d, would return 3 (the key).

I know how to do this in the case that the dictionary values are not an iterable, but I'm having trouble figuring out how to do it when it is an iterable.

Upvotes: 1

Views: 33

Answers (3)

Adam Smooch
Adam Smooch

Reputation: 1322

for k, v for d.items() is your friend here, it will allow you easy access to both key and values in the context of your for-loop.

To support multiple types for v (making comprehensions tough to read/follow), then use type(v) and some if statements.

Upvotes: 1

CodeKorn
CodeKorn

Reputation: 298

Using a list comprehension:

filtered_d = [k for k,v in d.items() if 1 in v]

Upvotes: 2

I'mahdi
I'mahdi

Reputation: 24049

You can use list comprehension.

d = {1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'], 3: [1, 'i', 'j']}

def ret_key_base_val(dct, val):
    return [k for k,v in dct.items() if val in v]

result = ret_key_base_val(d, 1)
print(result)
# [3]

Upvotes: 2

Related Questions