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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With