Loop through a dict changing keys

Alexander Kapps alex.kapps at web.de
Sat Oct 15 15:31:06 EDT 2011


On 15.10.2011 20:00, Gnarlodious wrote:
> What is the best way (Python 3) to loop through dict keys, examine the
> string, change them if needed, and save the changes to the same dict?
>
> So for input like this:
> {'Mobile': 'string', 'context': '<malicious code>', 'order': '7',
> 'time': 'True'}
>
> I want to booleanize 'True', turn '7' into an integer, escape
> '<malicious code>', and ignore 'string'.
>
> Any elegant Python way to do this?
>
> -- Gnarlie

I think JSON could be of some use, but I've not used it yet, 
otherwise something like this could do it:

#!/usr/bin/python

from cgi import escape

def convert(string):
     for conv in (int, lambda x: {'True': True, 'False': False}[x],
                  escape):
         try:
             return conv(string)
         except (KeyError, ValueError):
             pass
     return string


d = {'Mobile': 'string',
      'context': '<malicious code>',
      'order': '7',
      'time': 'True'}

print d

for key in d:
     d[key] = convert(d[key])

print d


$ ./conv.py
{'Mobile': 'string', 'order': '7', 'context': '<malicious code>', 
'time': 'True'}
{'Mobile': 'string', 'order': 7, 'context': '<malicious 
code>', 'time': True}



More information about the Python-list mailing list