Home > Back-end >  Filter values of a dictionary of lists, and return key
Filter values of a dictionary of lists, and return key

Time:12-07

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.

CodePudding user response:

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]

CodePudding user response:

Using a list comprehension:

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

CodePudding user response:

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.

  • Related