[Tutor] Question about Dictionaries
Steven D'Aprano
steve at pearwood.info
Tue Aug 17 02:17:22 CEST 2010
On Tue, 17 Aug 2010 03:44:33 am Chorn, Guillaume wrote:
> Hi All,
>
> I know that I can look up the value for a particular key in a
> dictionary, but can I look up the key associated with a particular
> value? I understand that this could be problematic from the
> standpoint of multiple keys having the same value, but even then I
> feel like Python could just return a list of keys with that value.
There is no built-in way of doing so, but it's easy to write your own.
def reverse_lookup(d, target, first_only=False):
found = []
for key, value in d.items():
if value == target:
if first_only: return key
found.append(key)
return found
Or if you want a one-liner, use a list-comp:
[k for (k,v) in d.items() if v == target]
--
Steven D'Aprano
More information about the Tutor
mailing list