在Python中使用键作为变量

时间:2013-06-10 08:55:53

标签: python orm peewee

对于我正在尝试做的事情,可能有一个术语,但它逃脱了我。我正在使用peewee在类中设置一些值,并希望迭代键和值列表以生成存储值的命令。

并非所有'集合'都包含类中的每个值,因此我只想包含我的数据集中包含的值。这就是我的成就:

for value in result['response']['docs']:
    for keys in value:
        print keys, value[keys]   # keys are "identifier, title, language'



#for value in result['response']['docs']:
#   collection =  Collection(
#       identifier = value['identifier'],
#       title = value['title'],
#       language = value['language'],
#       mediatype = value['mediatype'],
#       description = value['description'],
#       subject = value['subject'],
#       collection = value['collection'],
#       avg_rating = value['avg_rating'],
#       downloads = value['downloads'],
#       num_reviews = value['num_reviews'],
#       creator = value['creator'],
#       format = value['format'],
#       licenseurl = value['licenseurl'],
#       publisher = value['publisher'],
#       uploader = value['uploader'],
#       source = value['source'],
#       type = value['type'],
#       volume = value['volume']
#       )
#   collection.save()

2 个答案:

答案 0 :(得分:2)

for value in result['response']['docs']:
    Collection(**value).save()

有关**kwargs工作原理的解释,请参阅this问题。

答案 1 :(得分:1)

您是在谈论如何确定某个密钥是否在某个字典中?

>>> somedict = {'firstname': 'Samuel', 'lastname': 'Sample'}

>>> if somedict.get('firstname'):
>>>    print somedict['firstname']
Samuel

>>> print somedict.get('address', 'no address given'):
no address given

如果您想解决其他问题,请澄清您的问题。