如何创建按起止日期自动填充样本ID与对应VCF的字典?
解决Ion Reporter API样本VCF数据字典动态构建问题
问题分析
当前代码通过vcf_dict = {0: vcfs[0]}硬编码只提取了第一条样本数据,没有遍历API返回的全部样本记录,导致无法生成包含所有样本ID与对应VCF信息的字典。
解决方案
遍历API返回的样本列表,以样本ID作为字典的键,完整样本信息(含data_links、name等字段)作为值,用字典推导式可简洁实现动态构建:
修改后的完整代码:
def get_vcf(run_name, start_date, end_date, auth_token): headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': auth_token, } params = { 'format': 'json', 'name': run_name, 'start_date': start_date, 'end_date': end_date, } response = requests.get('https://ionreporter.thermofisher.com/api/v1/getvcf', params=params, headers=headers, verify=False) vcfs = response.json() # 动态构建样本ID到VCF信息的映射字典 vcf_dict = {sample['id']: sample for sample in vcfs} return vcfs, vcf_dict
关键说明
- 字典推导式
{sample['id']: sample for sample in vcfs}会自动遍历所有样本,无论返回多少条记录都能适配,无需手动指定数量。 - 如果API返回空列表,
vcf_dict会生成空字典,避免原代码中索引越界的报错问题。 - 若需兼容部分样本缺失
id字段的情况,可添加过滤逻辑:vcf_dict = {sample['id']: sample for sample in vcfs if 'id' in sample}
验证示例
假设API返回多条样本数据:
[ { "data_links": "ionreporter.thermofisher.com/api/v1/download?filePath=/data/IR/data/IR_Org/ion.reporter@lifetech.com/JohnSmithSample/Sample_20160429014705727/Sample_c150_2016-04-29-14-16-534.zip", "name": "Sample_c150_2016-04-29-14-16-534", "id": "ff808181545d90790154613336be0008" }, { "data_links": "ionreporter.thermofisher.com/api/v1/download?filePath=/data/IR/data/IR_Org/ion.reporter@lifetech.com/JohnSmithSample/Sample_20160501092345123/Sample_c200_2016-05-01-09-23-451.zip", "name": "Sample_c200_2016-05-01-09-23-451", "id": "ff808181545d90790154613336be0009" } ]
代码会生成如下字典:
{ "ff808181545d90790154613336be0008": {...}, # 对应第一个样本的完整数据 "ff808181545d90790154613336be0009": {...} # 对应第二个样本的完整数据 }
内容的提问来源于stack exchange,提问作者ClarkThark
相关产品推荐
相关产品推荐

