Keys order in dictionaries
W Isaac Carroll
icarroll at pobox.com
Thu Jun 26 23:17:04 EDT 2003
Brainwashed wrote:
> And the second thing that bothers me is assigning multiple values at once
> from dictionary. I mean:
>
> x, y, z = dict # where dict = { 'xx':.., 'yy':.., 'zz':.. }
>
> This works okay for me, if I know that dict is always of size 3 and there
> is the same order of keys:values.
Depending on the order things come out of a dictionary is a bad idea.
> But now I came to the point when this dict can have both - 3 or 4 items
> (same as this example from above, 'id' is the additional item that is not
> always present). And I want to assign x, y, z like I did before, but ommit
> id value. Is it possible to do at once, with some multiple assignment ?
> Maybe there is a way to specify what three items should be taken from dict
> and assigned to x, y, z? I know, I can always do something like:
> x = dict['xx']
> y = dict['yy'] and so on, but I'm just curious if some more complicated
> multiple assignment is possible in Python.
>
> How would you solve this problem?
First of all, remember that "dict" is a built-in function in Python, so
it shouldn't be used as a variable name.
How about
x, y, z = [foodict[key] for key in (key1, key2, key3)]
or
x, y, z = foodict[key1], foodict[key2], foodict[key3]
TTFN
More information about the Python-list
mailing list