Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?

Tags:

python

I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:

I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:

>>> type(myDict)
<type 'dict'>
>>> type(myDict[u'myKey'])
<type 'dict'>
>>> type(myDict[u'myKey'][u'myKey2'])
<type 'list'>
>>> type(myDict[u'myKey'][u'myKey2'][0])
<type 'unicode'>

I want to go through and make every string in it lowercase, i.e. every key and every string in every list.

How would you do this?

like image 644
David Avatar asked Nov 28 '22 12:11

David


1 Answers

Really simple way, though I'm not sure you'd call it Pythonic:

newDict = eval(repr(myDict).lower())

Saner way:

newDict = dict((k1.lower(),
                dict((k2.lower(),
                      [s.lower() for s in v2]) for k2, v2 in v1.iteritems()))
               for k1, v1 in myDict.iteritems())
like image 185
Nicholas Riley Avatar answered May 03 '23 03:05

Nicholas Riley