python 2字典根据它们的值加入1个字典连接

时间:2015-02-14 20:59:03

标签: python dictionary

这是情况
我有2个词典

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

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

我需要根据它们的值合并/加入它们作为连接条件。所以最终的输出看起来应该是

{
  D1K1: D2K1,
  D1K2: D2K2
}

在python中实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

这样的东西?

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())

答案 1 :(得分:0)

这是我提出的方法

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}