from dict to member vars...?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christopher J. Bottaro

    from dict to member vars...?

    Hello,

    Lets say I have a class instance with the following member vars: var1, x,
    size. Now lets say I have dict with the following keys: var1, x, size.
    Is there an easy way to *automatically* assign all the values in the dict
    to corresponding (member) vars of the same name as the dict keys?

    Thanks for the help.

  • Diez B. Roggisch

    #2
    Re: from dict to member vars...?

    Christopher J. Bottaro wrote:
    [color=blue]
    > Hello,
    >
    > Lets say I have a class instance with the following member vars: var1, x,
    > size. Now lets say I have dict with the following keys: var1, x, size.
    > Is there an easy way to *automatically* assign all the values in the dict
    > to corresponding (member) vars of the same name as the dict keys?[/color]

    d = dict(...)

    for key, val in d.items():
    setattr(o, key, val)

    --
    Regards,

    Diez B. Roggisch

    Comment

    • George Yoshida

      #3
      Re: from dict to member vars...?

      Christopher J. Bottaro wrote:
      [color=blue]
      > Lets say I have a class instance with the following member vars: var1, x,
      > size. Now lets say I have dict with the following keys: var1, x, size.
      > Is there an easy way to *automatically* assign all the values in the dict
      > to corresponding (member) vars of the same name as the dict keys?
      >
      > Thanks for the help.
      >[/color]

      If class is a new style class, you can do it this way:

      instance.__dict __.update(some_ dictionary)

      -- george

      Comment

      • Alex Martelli

        #4
        Re: from dict to member vars...?

        George Yoshida <ml@dynkin.co m> wrote:
        [color=blue]
        > Christopher J. Bottaro wrote:
        >[color=green]
        > > Lets say I have a class instance with the following member vars: var1, x,
        > > size. Now lets say I have dict with the following keys: var1, x, size.
        > > Is there an easy way to *automatically* assign all the values in the dict
        > > to corresponding (member) vars of the same name as the dict keys?
        > >
        > > Thanks for the help.[/color]
        >
        > If class is a new style class, you can do it this way:
        >
        > instance.__dict __.update(some_ dictionary)[/color]

        You can do this for instances of either classic and newstyle classes,
        _except_ newstyle classes which define __slots__ ...


        Alex

        Comment

        Working...