python - 为合并字典的每个键添加新值
问题描述
我正在尝试将 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.
解决方案
这里:
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 中的值都是唯一的。
推荐阅读
- node.js - 使用 node.js 返回 API 请求
- php - 无法通过php保存图像
- hibernate - 休眠@ManyToMany 坚持
- objective-c - 属性在 XCode 13 上有一个先前的声明
- android - 本地嵌入式机器学习套件库是否对谷歌服务器进行任何网络调用?
- php - Google API - 使用 Google_Service_MyBusinessBusinessInformation 获取位置
- django - 在 Heroku 上部署 Django 应用程序时,我收到错误代码 H10
- node.js - 关闭 mongodb 连接打开处理 jest express 应用程序测试
- google-apps-script - 从 Google Apps 脚本访问 github API 范围
- ruby-on-rails - NoMethodError: MinatoBackend::Application:Class 的未定义方法 `parent_name' || Ruby on rail ||