mass editing for keys in a dictionary

J

james_027

hi,

How could I transform something like this

dict_1 = {'customer_id':1, 'item_id':3, amount:100}

into

dict_2 = {'customer':1, 'item':3, amount:100}

thanks
james
 
A

Amit Khemka

hi,

How could I transform something like this

dict_1 = {'customer_id':1, 'item_id':3, amount:100}

into

dict_2 = {'customer':1, 'item':3, amount:100}

A one liner would be :
dict_2 = dict([(k.split('_')[0], v) for (k,v) in dict_1.iteritems()])

It would split the keys by '_' and use first part of split as the new key !

You must be aware be careful in cases where there are keys like
'customer_1' , 'customer_2', ...

Cheers,
 
B

Bruno Desthuilliers

james_027 a écrit :
hi,

How could I transform something like this

dict_1 = {'customer_id':1, 'item_id':3, amount:100}

into

dict_2 = {'customer':1, 'item':3, amount:100}

dict_2 = dict((k[:-3], v) for k, v in dict_1.iteritems())
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top