Updating python dictionary

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Sun Sep 7 18:02:04 EDT 2008


On Sun, 07 Sep 2008 14:51:32 -0700, andyhume at gmail.com wrote:

> 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?

You only have to loop through `my_dict`:

In [187]: %cpaste
Pasting code; enter '--' alone on the line to stop.
:MAPPING_DICT = {
:    'a': 'A',
:    'b': 'B',
:}
:
:my_dict = {
:    'a': '1',
:    'b': '2'
:}
:--

In [188]: dict((MAPPING_DICT[k], v) for k, v in my_dict.iteritems())
Out[188]: {'A': '1', 'B': '2'}

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list