Updating python dictionary

James Mills prologic at shortcircuit.net.au
Sun Sep 7 18:06:18 EDT 2008


Hi,

There is "never" a "clever" way
of doing anything, but:

$ cat test.py
MAPPING_DICT = {'a': 'A','b': 'B',}
my_dict = {'a': '1','b': '2'}
my_dict = dict((MAPPING_DICT[k], my_dict[k]) for k in my_dict)
print my_dict
$ python test.py
{'A': '1', 'B': '2'}
$

That should do the trick.

cheers
James

On Mon, Sep 8, 2008 at 7:51 AM, andyhume at gmail.com <andyhume at gmail.com> wrote:
> Hello...
>
> 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?
>
> Cheers,
> Andy.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"



More information about the Python-list mailing list