如何根据两个字典的值合并它们?

时间:2018-10-05 23:25:24

标签: python python-3.x

我目前有两个字典,其中包含核苷酸串作为键,并且其计数作为值。

示例:

dict1 = {GGA:64231, GAT: 66582}
dict2 = {TCC:64231, ATC: 66582}

我想制作一个新的字典,像这样:

dict3 = {'GGA:TCC':64231, 'GAT:ATC':66582} 

我该怎么做?

5 个答案:

答案 0 :(得分:1)

只需交换字典中的键/值对以构建新的键/值对(假设您具有唯一的值,并且字典都具有匹配的值):

Python 3:

dict1 = {'GGA':64231, 'GAT': 66582}
dict1 = {v:k for k,v in dict1.items()} # {66582: 'GAT', 64231: 'GGA'}
dict2 = {'TCC':64231, 'ATC': 66582}
dict2 = {v:k for k,v in dict2.items()} # {66582: 'ATC', 64231: 'TCC'}
dict3 = {"{}:{}".format(dict1[k],dict2[k]):k for k in dict1} # {'GGA:TCC': 64231, 'GAT:ATC': 66582}

Python 2.7使用iteritems()代替items()

答案 1 :(得分:0)

一种方法可能是尝试使用defaultdict

from collections import defaultdict

dict1 = {'GGA':64231, 'GAT': 66582}
dict2 = {'TCC':64231, 'ATC': 66582}

result_dict = defaultdict(list)
# read first dictionary and add value as key and key to list of values
for k, v in dict1.items(): result_dict[v].append(k)

# read other dictionary and add value as key and key to list of values 
for k, v in dict2.items(): result_dict[v].append(k)

# change key to value in dicitonary
result_dict = {':'.join(v):k for k, v in result_dict.items()}
print(result_dict)  

输出:

{'GAT:ATC': 66582, 'GGA:TCC': 64231}

答案 2 :(得分:0)

我将采用列表理解的方式,我认为它更具有Python风格:

dict1 = {GGA:64231, GAT: 66582}
dict2 = {TCC:64231, ATC: 66582}

new_dict = { x+":"+y:dict1[x] for x in dict1.keys() for y in dict2.keys() if dict1[x] == dict2[y]}   

这是输出:

{'GGA:TCC': 64231, 'GAT:ATC': 66582}

答案 3 :(得分:0)

我认为用键作为数字映射它们会更明智,例如,因为它们是定义因素。

a={i:[w] for w,i in dict1.items()}
b={i:w if i not in a else a[i]+[w] for w,i in dict2.items()}

输出

{64231: ['GGA', 'TCC'], 66582: ['GAT', 'ATC']}

或者您的情况

a={i:[w] for w,i in dict1.items()}
b={i:w if i not in a else ":".join(a[i]+[w]) for w,i in dict2.items()}

输出

{64231: 'GGA:TCC', 66582: 'GAT:ATC'}

答案 4 :(得分:0)

一个有趣的小问题。我的版本不搜索dict,它假设您的dict具有完善的信息,并且值可以按数字值排序。

dict1 = {"GGA": 64231, "GAT": 66582}
dict2 = {"TCC": 64231, "ATC": 66582}

dict3 = {
    "%s:%s" % (k, l): v
    for (k, v), (l, b) in zip(
        sorted(dict1.items(), key=lambda x: x[1]),
        sorted(dict2.items(), key=lambda x: x[1]),
    )
}
print(dict3)

我会说@TheoretiCAL的答案可能是最好的。

相关问题