Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary to variable assignments based on key value to variable name

Basically, I want to take a

Dictionary like { "a":"bar", "b":"blah", "c":"abc", "d":"nada" }

and use it to set variables (in an Object) which have the same name as a key in the dictionary.

class Foo(object)
{
    self.a = ""
    self.b = ""
    self.c = ""
}

So in the the end self.a = "bar", self.b = "blah", etc... (and key "d" is ignored)

Any ideas?

like image 591
Art Avatar asked May 10 '10 00:05

Art


1 Answers

Translating your class statement to Python,

class Foo(object):
  def __init__(self):
    self.a = self.b = self.c = ''
  def fromdict(self, d):
    for k in d:
      if hasattr(self, k):
        setattr(self, k, d[k])

the fromdict method seems to have the functionality you request.

like image 181
Alex Martelli Avatar answered Sep 19 '22 11:09

Alex Martelli