I have a dictionary I would like to insert into a mongodb. The code works but I would like to insert it with both keys AND values moved to lowercase for ease of searching later. Some example data would be:
{'Publisher': u'TSR', 'Language': u'en', 'Title': u'The Silent Blade', 'Authors': [u'R. A. Salvatore'], 'ISBN-13': u'9780786913886', 'Year': u'1998'}
{'Publisher': u'Houghton Mifflin Harcourt', 'Language': u'en', 'Title': u'A Field Guide To Mushrooms, North America', 'Authors': [u'Kent H. McKnight', u'Roger Tory Peterson', u'Vera B. McKnight'], 'ISBN-13': u'9780395910900', 'Year': u'1998'}
Notice the second option has multiple authors, so a list in the dictionary. I am still new to python and this has kept me up many nights. Can't seem to get my head wrapped around how to access them. I can change the case of the key case with this
book_data = {k.lower(): v for k, v in book_data.items()} #keys
book_data = {v.lower(): k for k, v in book_data.items()} #values
But I have tried to mod this from keys to values and just put them back to back, but it fails on the list in second example. What is the best way to iterate over the entire dictionary and lowercase the keys as values? Most of my searches just return changing the case of the keys.
I'd define a function to recursively lowercase a value, and then use it in a dict comprehension:
import types
def lowerValues(arg):
# Handle iterables
if hasattr(arg, "__iter__"):
return [lowerValues(item) for item in arg]
elif isinstance(arg, types.StringTypes):
return arg.lower()
else:
return arg
book_data = {k.lower() : lowerValues(v) for k,v in book_data.items()}