converting dict to object

Discussion in 'Python' started by rieh25, Dec 2, 2006.

  1. rieh25

    rieh25 Guest

    rieh25, Dec 2, 2006
    #1
    1. Advertising

  2. rieh25

    Carl D. Roth Guest

    On Fri, 01 Dec 2006 17:48:40 -0800, rieh25 wrote:

    > If I have a dictionary such as:
    >
    > d = {'a' : 1, 'b' : 2}
    >
    > is there a way to convert it into an object o, such as:
    >
    > o.a = 1
    > o.b = 2


    Rather, the question could be asked the other way around: how can you
    convert that object into a dict?

    The attributes in 'o' are part of its '__dict__' attribute, which is a
    dictionary. That is,

    o.a = 1

    is equivalent to

    o.__dict__['a'] = 1

    If you already have a dictionary 'd', you can overlay it onto the object's
    attributes with

    o.__dict__.update(d)

    Carl
    Carl D. Roth, Dec 2, 2006
    #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. Skip Montanaro
    Replies:
    0
    Views:
    403
    Skip Montanaro
    Aug 15, 2003
  2. Alexander Kozlovsky

    dict!ident as equivalent of dict["ident"]

    Alexander Kozlovsky, May 21, 2006, in forum: Python
    Replies:
    5
    Views:
    348
    Alexander Kozlovsky
    May 22, 2006
  3. Gabriel Genellina

    Re: converting dict to object

    Gabriel Genellina, Dec 2, 2006, in forum: Python
    Replies:
    9
    Views:
    1,215
    John Machin
    Dec 3, 2006
  4. Paul Melis

    dict.has_key(x) versus 'x in dict'

    Paul Melis, Dec 6, 2006, in forum: Python
    Replies:
    48
    Views:
    1,301
    Kent Johnson
    Dec 15, 2006
  5. Almad
    Replies:
    8
    Views:
    390
    Terry Reedy
    Dec 14, 2006
Loading...

Share This Page