user7692855
user7692855

Reputation: 1428

Mapping Python Dict keys to another Dict

Due to some poor planning I have a script that expects a python dict with certain keys however, the other script that creates this dict is using a different naming convention.

Unfortunately, due to translations that have already taken place it looks like I'll need to convert the dict keys.

Basically go from

 {'oldKey':'data'}

to

 {'newKey':'data'}

I was thinking of creating a dict:

 {'oldKey':'newKey'}

and iterate through the dict to convert from oldKey to newKey however is this the most efficient/pythonic way to do it?

Upvotes: 4

Views: 4851

Answers (2)

Ritwik Bandyopadhyay
Ritwik Bandyopadhyay

Reputation: 175

This will solve your problem:

new_dict={key_map[oldkey]: vals for (oldkey, vals) in old_dict.items()}

Upvotes: 0

Captain Whippet
Captain Whippet

Reputation: 2223

I can think of a couple of ways to do this which use dictionaries, but one of them might be more efficient depending on the coverage of the key usage.

a) With a dictionary comprehension:

old_dict = {'oldkey1': 'val1', 'oldkey2': 'val2',
            'oldkey3': 'val3', 'oldkey4': 'val4',
            'oldkey5': 'val5'}

key_map = {'oldkey1': 'newkey1', 'oldkey2': 'newkey2',
           'oldkey3': 'newkey3', 'oldkey4': 'newkey4',
           'oldkey5': 'newkey5'}

new_dict = {newkey: old_dict[oldkey] for (oldkey, newkey) in key_map.iteritems()}

print new_dict['newkey1']

b) With a simple class that does the mapping. (Note that I have switched the order of key/value in key_map in this example.) This might be more efficient because it will use lazy evaluation - no need to iterate through all the keys - which may save time if not all the keys are used.

class DictMap(object):

    def __init__(self, key_map, old_dict):
        self.key_map = key_map
        self.old_dict = old_dict

    def __getitem__(self, key):
        return self.old_dict[self.key_map[key]]

key_map = {'newkey1': 'oldkey1',
           'newkey2': 'oldkey2',
           'newkey3': 'oldkey3',
           'newkey4': 'oldkey4',
           'newkey5': 'oldkey5'}

new_dict2 = DictMap(key_map, old_dict)

print new_dict2['newkey1']

Upvotes: 2

Related Questions