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': '&lt;malicious code&gt;', 'time': True}
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to