Re: Keys order in dictionaries

Discussion in 'Python' started by W Isaac Carroll, Jun 27, 2003.

  1. 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
    W Isaac Carroll, Jun 27, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Brainwashed

    Keys order in dictionaries

    Brainwashed, Jun 27, 2003, in forum: Python
    Replies:
    2
    Views:
    762
    Duncan Booth
    Jun 27, 2003
  2. =?ISO-8859-1?Q?Gerhard_H=E4ring?=

    Re: Keys order in dictionaries

    =?ISO-8859-1?Q?Gerhard_H=E4ring?=, Jun 27, 2003, in forum: Python
    Replies:
    0
    Views:
    674
    =?ISO-8859-1?Q?Gerhard_H=E4ring?=
    Jun 27, 2003
  3. ProvoWallis
    Replies:
    7
    Views:
    415
    ProvoWallis
    Dec 7, 2005
  4. lysdexia
    Replies:
    6
    Views:
    493
    John Machin
    Dec 2, 2007
  5. Brandon
    Replies:
    12
    Views:
    487
    Brandon
    Aug 15, 2008
Loading...

Share This Page