Setting variable values from dictionary

Discussion in 'Python' started by Sean Berry, Apr 23, 2004.

  1. Sean Berry

    Sean Berry Guest

    If I have a dictionary like the following:

    {'category' : 2, 'shape', 4}

    How can I use this to make
    category = 2 and
    shape = 4.

    I want to be able to do this regardless of the dict values type. So:

    {'cateogry' : 2, 'shape' : 'circle'}

    will work as well.


    Thanks in advance for any help. You guys rock.

    --
     
    Sean Berry, Apr 23, 2004
    #1
    1. Advertising

  2. Sean Berry

    Dave Kuhlman Guest

    Sean Berry wrote:

    > If I have a dictionary like the following:
    >
    > {'category' : 2, 'shape', 4}
    >
    > How can I use this to make
    > category = 2 and
    > shape = 4.
    >
    > I want to be able to do this regardless of the dict values type.
    > So:
    >
    > {'cateogry' : 2, 'shape' : 'circle'}
    >
    > will work as well.


    locals().update(mydict)

    Oops. I just actually read the docs:

    locals( )
    Update and return a dictionary representing the current
    local symbol table. *Warning*: The contents of this
    dictionary should not be modified; changes may not affect
    the values of local variables used by the interpreter.

    [Emphasis added.]

    So, perhaps, the following is to be preferred:

    for name, value in mydict.items():
    exec('%s = %s' % (name, value))

    But, what do you want to do about name clashes?

    Dave

    --
    Dave Kuhlman
    http://www.rexx.com/~dkuhlman
     
    Dave Kuhlman, Apr 23, 2004
    #2
    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. Ilias Lazaridis
    Replies:
    6
    Views:
    485
    Ilias Lazaridis
    Feb 21, 2006
  2. james_027
    Replies:
    1
    Views:
    364
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  3. Navkirat Singh
    Replies:
    6
    Views:
    3,346
    Navkirat Singh
    Jul 29, 2010
  4. Chris Rebert
    Replies:
    0
    Views:
    573
    Chris Rebert
    Jul 29, 2010
  5. Fox

    dictionary within dictionary

    Fox, Mar 8, 2005, in forum: ASP General
    Replies:
    5
    Views:
    214
    Michael D. Kersey
    Mar 13, 2005
Loading...

Share This Page