Loop through a dict changing keys

Chris Angelico rosuav at gmail.com
Mon Oct 17 06:43:31 EDT 2011


On Mon, Oct 17, 2011 at 5:20 AM, Gnarlodious <gnarlodious at gmail.com> wrote:
> On Oct 15, 5:53 pm, PoD <p... at internode.on.net> wrote:
>
>> types={'Mobile':str,'context':str,'order':int,'time':bool}
>>
>> for k,v in data.items():
>>     data[k] = types[k](v)
>
> Thanks for the tip, I didn't know you could do that. I ended up
> filtering the values the bulky way, but it gives me total control over
> what internet users feed my program.

It should be noted that this will not in any way sanitize
data['context']. It calls the str() function on it, thus ensuring that
it's a string, but that's all. If you're needing to deal with
(potentially) malicious input, you'll want to swap in a function that
escapes it in some way (if it's going into a database, your database
engine will usually provide a 'quote' or 'escape' function; if it's to
go into a web page, I think cgi.escape is what you want).

ChrisA



More information about the Python-list mailing list