On Sep 7, 3:37 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Sep 8, 7:51 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> 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?
>
> Is this homework?
>
> There seems to be an implicit assumption in the answers so far that
> your mapping is a 1:1 mapping of all possible input keys.
>
> If it doesn't include all possible input keys, answers will crash with
> a KeyError. If there are any many:1 elements in the mapping (for
> example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code
> in some checks for this.

Thats exactly why I did an explicit check in my post, so as to make
sure that such a collision could not occur. It would seem that
something along what I posted would be safer, if less elegant, than
the others.
Cheers, MK
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to