Loop through a dict changing keys

PoD pod at internode.on.net
Sun Oct 16 07:12:31 EDT 2011


On Sun, 16 Oct 2011 00:18:40 -0700, Jon Clements wrote:

> On Oct 16, 12:53 am, PoD <p... at internode.on.net> wrote:
>> On Sat, 15 Oct 2011 11:00:17 -0700, 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
>>
>> How about
>>
>> data = {
>>     'Mobile': 'string',
>>     'context': '<malicious code>',
>>     'order': '7',
>>     'time': 'True'}
>> types={'Mobile':str,'context':str,'order':int,'time':bool}
>>
>> for k,v in data.items():
>>     data[k] = types[k](v)
> 
> Bit of nit-picking, but:
> 
>>>> bool('True')
> True
>>>> bool('False')
> True
>>>> bool('')
> False

Oops :) Brain fade.



More information about the Python-list mailing list