3

I have two dictionaries I want to merge using both keys and values. The first is an ordered dictionary, while the second is a regular one. Both dicts have the same length.

ord_dict = OrderedDict([(0, 369670), (1, 370622), (2, 267034), ...])
reg_dict = {0: (0, 0), 1: (0, 1), 2: (0, 2), ...}

The desired result is a new dict where the key is the tuple of reg_dict and the value is the second element of each tuple in ord_dict.

In this example, the result should look like this:

merged_dict = {(0, 0): 369679, (0, 1): 370622, (0, 2): 267034, ...}

How to do this?

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
FaCoffee
  • 7,609
  • 28
  • 99
  • 174

2 Answers2

2

You can use a dict comprehension:

merged_dict = {reg_dict[k]: v for k, v in ord_dict.items()}

This will result in

{(0, 0): 369670, (0, 1): 370622, (0, 2): 267034}
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

I'm not sure how you retreive a value from an OrderedDict but if it was a normal dict you could do something like this:

merged_dict = dict([ (v, ord_dict.get(k)) for k, v in reg_dict.iteritems() ])
Juanín
  • 841
  • 6
  • 16