[Python-ideas] Remapping a table's keys

Chris Rebert pyideas at rebertia.com
Fri Nov 5 02:20:20 CET 2010


On Thu, Nov 4, 2010 at 6:07 PM, Andrey Fedorov <anfedorov at gmail.com> wrote:
> Hi guys,
> I often run into the problem when I need to systematically rename a bunch of
> keys in a table. For example, a JSON API returns an object where I need to
> map "Media Cost" to "adjusted_partner_cost", "Impressions" to "bid_count",
> etc. One way of doing this is:
>
> key_map = {
>     'Media Cost': 'adjusted_partner_cost',
>     'Impressions': 'bids_won',
>     'Day': 'date'
> }
> mykeys = {}
> for k, v in dict_from_elsewhere.items():
>   if k in key_map:
>     ret[key_map[k]] = v
>   else:
>     ret[k] = dict_from_elsewhere[k]

# Requires Python 2.7+ (dict comprehension)
ret = {key_map.get(k, k) : v for k,v in dict_from_elsewhere.items()}

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-ideas mailing list