0

Is there a standard Python function to build a dictionary out of two, where the values from the first one are linked to the keys of the seconds?

dict_1= {'sparrow': 'cat', 'mouse': 'cat', 'deer': 'wolf'}  # prey: predator
dict_2 = {'cat': 'rural', 'wolf': 'forest'}  # predator: predator_habitat 
# my solution using a dictionary comprehension
{key: dict_2[val] for key, val in dict_1.items()}
# gives
{'sparrow': 'rural', 'mouse': 'rural', 'deer': 'forest'}  # prey: predator_habitat

Since the dictionaries can have million of records, computation time (and efficient code) matters. Trying to adopt a solution to this similar but different question

from collections import OrderedDict
OrderedDict(zip(dict_1.keys(), dict_2.values()))
# gives a un-wanted result:
{'cat': 'cat', 'wolf': 'cat'}

Note: I do not want to merge the dictionaries into on, keeping the key:value relations like in this question.

Qaswed
  • 3,649
  • 7
  • 27
  • 47
  • No standard function for what it probably not a common operation. Your dictionary comprehension seems short and clear enough that there would be little benefit trying to do anything else. I think though you meant to say your solution is `{key: dict_2[val] for key, val in dict_1.items()}` (you switched the dictionaries in your post) – Duncan Nov 26 '19 at 14:54
  • @Duncan yes, I accidentelly switshed the dictionaries - thank you! – Qaswed Nov 26 '19 at 14:59

0 Answers0