首页 > 解决方案 > 为合并字典的每个键添加新值

问题描述

我正在尝试将 3 个字典合并在一起并仅保留唯一值。在为这些合并字典中的每个键添加一些新值时,我遇到了问题。我要添加的值取自另一个字典。我进行了如下操作:

        fileName1 = hmmFiles[0]
        fileName2 = hmmFiles[1]
        fileName3 = hmmFiles[2]
        dictF = generateDict(fileName1)
        dicts = generateDict(fileName2)
        dictT = generateDict(fileName3)
        dictPreUnique = {**dictF, **dictS}
        dictUnique = {**dictPreUnique, **dictT}
        for d in dictUnique:
            for di in dict1:
                cas_Id = di[:-1]
                if dictUnique[d][-1] == cas_Id:
                    values.append(dict1[di])
                    dictUniqueFinal[d] = dictUnique[d]
                    dictUniqueFinal[d].append(values)
                    dictUnique.update(dictUniqueFinal)
        print(dictUnique)

其中 generateDict 是我创建的用于形成字典的函数,而 dict1 是形式的字典:

'HMM1_2': 'II-C 0.86', ...
} ``` 
and dictUnique is a dictionary of form : 
```{'ACNR01000019.1_63_ID=1_63': (66215, 66769, -1, 'cas6', 1), 
'ACNR01000019.1_64_ID=1_64': (66780, 67784, -1, 'cas7', 1),...
} ```
I want to check if the number of each key of dict1 example HMM1_**1** is the same as the last value of dictUnique. If they are, I want to add values like **I-F 1.0** or **II-C 0.86** in dictUnique.
After this code I dont get the wanted result, I get only the merged dictionaries without the wanted values added. 
PLease help.

标签: pythonbioinformatics

解决方案


这里:

d1 = {'cats':5,
      'dogs':7,
      'rats':9,
      'pigs':3}
d2 = {'cats':3,
      'yaks':9,
      'rats':1,
      'bats':6}
d3 = {'bugs':9,
      'dogs':2,
      'yaks':1,
      'rams':3}
d4 = {}
for d in [d1,d2,d3]:
    for value in d.values():
        if value not in d4.values():
            d4.update({list(d.keys())[list(d.values()).index(value)]:value})
print(d4)

结果:

{'cats': 5, 
 'dogs': 2, 
 'rats': 1, 
 'pigs': 3, 
 'bats': 6, 
 'bugs': 9}

d4 中的值都是唯一的。


推荐阅读