0

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()
Justin
  • 367
  • 1
  • 5
  • 15

2 Answers2

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

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

Community
  • 1
  • 1
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • That is really neat. Worked great. Bookmarked the documentation on kwargs for further reading, need some time to let it sink in. – Justin Jun 10 '13 at 09:20
1

Are you talking about how to find out whether a key is in a dict or not?

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

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

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

If there is a different problem you'd like to solve, please clarify your question.

mawimawi
  • 4,222
  • 3
  • 33
  • 52
  • I wanted to avoid checking over each keypair value, because the code would get long and messy trying to hammer out different exceptions. Rather, I would like to just push the keypairs that are available into the values for the Collection for saving. Bakuriu's response was very nice. – Justin Jun 10 '13 at 09:23