1

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.

2 Answers 2

1

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()} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that helped out quite a bit.
1

Do the whole thing in one step:

book_data = {k.lower(): str(v).lower() for k, v in dict.items()}

2 Comments

Your solution will fail on examples provided in the question.
You are right Sanyash, I forgot to add the str() first. I tried in both now and it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.