开发者

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

开发者 https://www.devze.com 2022-12-30 04:48 出处:网络
Basically, I want to take a Dictionary like { \"a\":\"bar\", \"b\":\"blah\", \"c\":\"abc\", \"d\":\"nada\" }

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)
{开发者_如何学C
    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?


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.


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)


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

精彩评论

暂无评论...
验证码 换一张
取 消