Python字典根据键值对变量名进行变量赋值

标签 python variables dictionary variable-assignment

基本上,我想拍一张

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

这样的字典

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

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

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

有什么想法吗?

最佳答案

将你的 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])

fromdict 方法似乎具有您要求的功能。

关于Python字典根据键值对变量名进行变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2799790/

相关文章:

c++ - 指针与引用

html - 如何创建 "variables"以便以后搜索和替换(有点像 HTML 中的合并字段

JAVA - MultiMaps 和entryset()

c# - 在 C# 中将三个元素存储在一个变量中

python - 如何将 Python 字典转换为 html 表?

python - 在Kivy中独立移动多个Widget

python - 如何使用 SpiffWorkflow 创建任务?

python - Django model.objects.all() 在正常调用时给出列表索引超出范围

python - 无法弄清楚 pytorch 代码中的就地操作?

mysql - 如何在 Sql View 查询中引用值