Extracting list of keys from 2-key dictionary

Remco Gerlich scarblac-spamtrap at pino.selwerd.cx
Mon Dec 13 05:21:03 EST 1999


mdfranz at my-deja.com <mdfranz at my-deja.com> wrote:
> I'm porting a script from perl that uses:
> 
>     dict[a,b] instead of $hash{$a}{$b}
> 
> My goal is to get a unique list of the second keys for a value, when a=x
> 
> In perl, this can be done with:
> 
>     @list = keys %{$hash{x}}
> 
> Is there a quicker/easier way in python than the snippet below to do
> this?
> 
>    for a,b in dict.keys():
>         if dict.has_key(x,b):
>               if b not in list:
>                       list.append(b)

I'm not sure what you mean. You have a dict of which the keys are
tuples (a,b), and you want to find a list of unique b's given a=x?
But those b's are unique automatically, since a is fixed, and there
can be only one key (a,b) for each b.

So I would do:

list = []
for a,b in dict.keys():
    if a == x: list.append(b)

But it depends on your data to know if it could be faster, I suppose.
If you have *many* keys, and a=x for only a few of them, and b has a 
limited range, you should try out all the possible (x,b) pairs with has_key.

-- 
Remco Gerlich,  scarblac at pino.selwerd.cx
"This gubblick contains many nonsklarkish English flutzpahs, but the
 overall pluggandisp can be glorked from context"  (David Moser)



More information about the Python-list mailing list