views:

186

answers:

2

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?

+1  A: 
class Foo(object):
    a, b, c = "", "", ""

foo = Foo()

_dict = { "a":"bar", "b":"blah", "c":"abc", "d":"nada" }
for k,v in _dict.iteritems():
    if hasattr(foo, k):
        setattr(foo, k, v)
rebus
I like this approach slightly better. Might be worth noting though that iteritems() is removed in 3.x in favour of items(). Not sure what version the OP is using.
Peter
+1  A: 

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.

Alex Martelli