10

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?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3
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)

1 Comment

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.
2

Another option is to use argument unpacking:

class Foo(object):
     def __init__(self, a='', b='', c='', **kwargs)
         self.a = a
         self.b = b
         self.c = c

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

f = Foo(**d)

2 Comments

Can you please explain this "argument unpacking"?
@Tengis: d = {"a": 1, "b": 2}; f(**d) is the same as f(a=1, b=2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.