Python字典到变量赋值,基于键值到变量名

Art*_*Art 9 python variables dictionary variable-assignment

基本上,我想拿一个

字典就像 { "a":"bar", "b":"blah", "c":"abc", "d":"nada" }

并使用它来设置与字典中的键同名的变量(在Object中).

class Foo(object)
{
    self.a = ""
    self.b = ""
    self.c = ""
}
Run Code Online (Sandbox Code Playgroud)

所以在最后self.a ="bar",self.b ="blah"等...(并忽略键"d")

有任何想法吗?

Ale*_*lli 5

将您的class语句翻译为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])
Run Code Online (Sandbox Code Playgroud)

fromdict方法似乎具有您请求的功能.


Dav*_*cic 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)
Run Code Online (Sandbox Code Playgroud)