1ksj8jdnu36flksf
1ksj8jdnu36flksf

Reputation: 225

Mapping between Dictionaries in Python

I have two dictionaries and I want to map them based on below conditions :

  1. The Result dictionary map_result should have all the items from resp_dict but the keys should be picked from map_dict in case the keys of resp_dict match with the values in map_dict.
  2. If the key in resp_dict does not exists in map_dict then, that key,value must be as is passed to the map_result (Result dictionary).
  3. If there is any item present in map_dict but not in resp_dict then ignore that completely.

Below is the example of what Im looking -

resp_dict = {'name': "Rodney",
             'prop_9986': "http://rodrnylynch.com",
             'prop_7635': "7164084552",
             'status': "Active",
             'prop_5346': "pkunch"}
map_dict = {'user_name': "name",
            'self_website': "prop_9986",
            'account_number': "prop_7635",
            'page_name': "profile_page"}

map_result = {'user_name': "Rodney",
              'self_website': "http://rodrnylynch.com",
              'account_number': "7164084552",
              'status': "Active",
              'prop_5346': "pkunch"}

I tried something like below which basically meets condition 1 & 3 mentioned above but not the 2nd condition.

map_result = dict((k, resp_dict[map_dict[k]]) for k in map_dict if map_dict[k] in resp_dict)

>>> map_result
{'self_website': 'http://rodrnylynch.com', 'user_name': 'Rodney', 'account_number': '7164084552'}

Can someone help me with the best approach to achieve this.

Thank you!

Upvotes: 2

Views: 381

Answers (1)

Kelly Bundy
Kelly Bundy

Reputation: 27660

Prepare the reverse name lookup:

name = {v: k for k, v in map_dict.items()}

Then use it:

map_result = {name.get(k, k): v for k, v in resp_dict.items()}

Upvotes: 1

Related Questions