Search code examples
pythonormpeewee

Using Keys as Variables in Python


There is probably a term for what I'm attempting to do, but it escapes me. I'm using peewee to set some values in a class, and want to iterate through a list of keys and values to generate the command to store the values.

Not all 'collections' contain each of the values within the class, so I want to just include the ones that are contained within my data set. This is how far I've made it:

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

Solution

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

    See this question for an explanation on how **kwargs work.