Updating python dictionary

MK Bernard mkbernard.dev at gmail.com
Sun Sep 7 18:04:34 EDT 2008


On Sep 7, 2:51 pm, "andyh... at gmail.com" <andyh... 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.

You could accomplish this with something similar to the following:
new_dict = {}
for x in MAPPING_DICT.keys():
	if x in my_dict.keys():
		new_dict[MAPPING_DICT[x]] = my_dict[x]

Although there is probably a better solution to the problem your
having. Perhaps more details could help us lead in you the right
direction?

Cheers, MK



More information about the Python-list mailing list