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. -- http://mail.python.org/mailman/listinfo/python-list