Howto find dict members from a list of keys

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Thu Mar 8 09:33:17 CET 2007


On Thu, 08 Mar 2007 09:20:20 +0100, Alexander Eisenhuth wrote:

> Hello,
> 
> what algo do you use, when you want to find the dict values from d, with members 
> of l. Following example:
> 
>  >>> d = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9,9:10}
>  >>> l = [7,8]
>  >>> found_dic_members = <yourCode>
>  >>> print found_dict_members
> [8,9]

It depends. 

If all of the values in d are usable as keys (that is, all the values
are hashable, so no lists or sets etc.) then you can build a
reverse-lookup dictionary and use that for fast look-ups.

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> rd = dict(zip(d.values(), d.keys()))
>>> rd
{'a': 1, 'c': 3, 'b': 2}

But if you can't do that, you're stuck with a slow search through the
entire dict:

def reverse_search(d, target):
    """Return the first key of dict d that matches the target value."""
    for key, value in d.iteritems():
        if value == target:
            return key
    raise KeyError('no key found matching that value')


In both cases though, you have to think about what you want to happen for
duplicated values.



-- 
Steven D'Aprano 




More information about the Python-list mailing list