Updating python dictionary
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sun Sep 7 18:18:49 EDT 2008
En Sun, 07 Sep 2008 18:51:32 -0300, andyhume at gmail.com <andyhume at gmail.com> escribió:
> I have a dict of key/values and I want to change the keys in it, based
> on another mapping dictionary. An example follows:
>
> MAPPING_DICT = {
> 'a': 'A',
> 'b': 'B',
> }
>
> my_dict = {
> 'a': '1',
> 'b': '2'
> }
>
> I want the finished my_dict to look like:
>
> my_dict = {
> 'A': '1',
> 'B': '2'
> }
>
> Whereby the keys in the original my_dict have been swapped out for the
> keys mapped in MAPPING_DICT.
>
> Is there a clever way to do this, or should I loop through both,
> essentially creating a brand new dict?
Exactly. You can do that in one pass:
my_new_dict = dict((MAPPING_DICT[k],v) for (k,v) in my_dict.iteritems())
That's enough if MAPPING_DICT always contains all the keys. If you want to keep old keys that aren't in MAPPING_DICT unchanged, use MAPPING_DICT.get(k,k) instead. Other corner cases include many-to-one mappings, and incomplete mappings where a replacement key is also an unmapped old key.
--
Gabriel Genellina
More information about the Python-list
mailing list