Home > Net >  Efficient way to find key by value in Python dict where dict values are iterables
Efficient way to find key by value in Python dict where dict values are iterables

Time:11-04

I have an iterable of unique numbers:

lst = [14, 11, 8, 55]

where every value is somewhere among numbers of dict's iterable-values, say lists:

dict_itms.items() = dict_items([(1, [0, 1, 2, 3]), (2, [11, 14, 12]), (3, [30, 8, 42]), (4, [55, 6])])

I have to find each lst element in a dict such a way that, finally, I would have a list of keys pairwise against each element in lst.

This method:

keys_ = []
for a in lst:
    for k, v in dict_itms.items():
        if a in v:
            keys_  = [k]
            break
        else:
            continue

gives: [2, 2, 3, 4]

Is there more efficient way to find every key pairwise against each number to find?

CodePudding user response:

You can use any in a list comprehension:

print([k for k,v in dict_itms.items() if any(x in lst for x in v)])

Output:

[2, 3, 4]
Update

According to this answer not set(v).isdisjoint(lst) is the fastest:

print([k for k,v in dict_itms.items() if not set(v).isdisjoint(lst)])

CodePudding user response:

A simple and Pythonic implementation:

d = dict([(1, [0, 1, 2, 3]), (2, [11, 14, 12]), (3, [30, 8, 42]), (4, [55, 6])])

xs = [14, 11, 8, 55]

keys = [k for k, v in d.items() if set(v).intersection(xs)]
print(keys)

However, this doesn't duplicate the 2 key, which your example does - not sure if that's behaviour you need?

  • Related