daydreamer
daydreamer

Reputation: 92119

python 2 dictionaries into 1 dictionary join based on their values

Here is the situation
I have 2 dictionaries as

dict1
{ 
  D1K1: (v1, v2),
  D1K2: (v3, v4)
}

dict2
{ 
  D2K1: (v1, v2),
  D2K2: (v3, v4)
}

I need to merge/join them based on their values as join condition. so the final output should look like

{
  D1K1: D2K1,
  D1K2: D2K2
}

What's the best way to achieve this in python?

Upvotes: 0

Views: 90

Answers (2)

volcano
volcano

Reputation: 3582

This is the approach I came up with

from collections import defaultdict
from itertools import chain
# create joint list of key-values, and sort it by values
dicts_merged = sorted(chain(dict1.iteritems(), dict2.iteritems()), key=itemgetter(1))

# Rearrange by values
grouped_dict = defaultdict(list)
for key, val in dicts_merged:
    grouped_dict[val].append(key)

# Final step
result = {v[0] : v[1] for v in grouped_dict if len[v] >= 2}

Upvotes: 0

thebjorn
thebjorn

Reputation: 27321

Something like this?

dict1 = { 
  'D1K1': ('v1', 'v2'),
  'D1K2': ('v3', 'v4')
}

dict2 = { 
  'D2K1': ('v1', 'v2'),
  'D2K2': ('v3', 'v4')
}

# reverse dict2. this randomly chooses one of the possible mappings
# if there are more than one key with the same value..
inv2 = dict((v, k) for k, v in dict2.items())

# this assumes that there will always be a reverse mapping in dict2 
# for all values in dict1 (use inv2.get(v, default_value) if that is
# not the case).
print dict((k, inv2[v]) for k, v in dict1.items())

Upvotes: 1

Related Questions