Extracting list of keys from 2-key dictionary

Tim Peters tim_one at email.msn.com
Mon Dec 13 03:43:15 EST 1999


[mdfranz at my-deja.com]
> 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}}
>

No, it can't (see below before yelling at me <wink>).

> 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)

You used a 2-level hash in your Perl, but a 1-level dict in your Python.
Perl similar to your Python would use

    $hash{$a, $b}

relying on Perl's $SUBSCRIPT_SEPARATOR to make "$a$;$b" the key to a
one-level hash (while your Python dict[a, b] uses the 2-tuple (a, b) as the
key to a one-level dict).

You can also use a 2-level dict of dicts in Python.  Then extraction is the
(very close to your Perl) one-liner:

    list = hash[x].keys()

Doing this operation with a 1-level hash/dict using compound keys is clumsy
in both languages.

dict-is-short-for-dictator-cuz-gui-was-already-in-use-ly y'rs  - tim






More information about the Python-list mailing list