Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字典保存到模型对象_Python_Dictionary - Fatal编程技术网

Python 将字典保存到模型对象

Python 将字典保存到模型对象,python,dictionary,Python,Dictionary,我有一本这样的字典: {'company_name': 'Google', 'title': 'headline', ...} 我知道我可以使用以下方式存储值: user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...) 但是,如果我有许多表单字段,这就不好了 有没有办法不用硬编码就能完成所有的地图?字典的键值与他的模型相同。使用dic.iteritems()中的键值在字典上循环

我有一本这样的字典:

{'company_name': 'Google', 'title': 'headline', ...}
我知道我可以使用以下方式存储值:

user = User(company_name=data_db_form['company_name'], title=data_db_form['title']...)
但是,如果我有许多表单字段,这就不好了


有没有办法不用硬编码就能完成所有的地图?字典的键值与他的模型相同。

使用dic.iteritems()中的键值
在字典上循环:
,然后在每次迭代中,您的键值和
谷歌
标题
等中都有
公司名称
标题
,等等。

您可以使用以下内容:

user = User(**data_db_form)

以下是完整的示例:

class User():
    def __init__(self, company_name='unknown', title='unknown'):
        self.company_name = company_name
        self.title = title

data_db_form = {'company_name': 'Google', 'title': 'headline'}

user = User(**data_db_form)

print user.company_name # prints Google
print user.title        # prints headline

你试过把字典打开吗<代码>用户=用户(**数据\数据库\表格)?