首页 > 解决方案 > Python如何动态合并另一个字典列表中的字典内容

问题描述

我对 Python 不是很熟悉,我真的不知道如何得到想要的结果,我花了一些时间检查以前的问题和答案,但什么也没有。

假设我有两个字典列表:

清单 A:

[{'g_type': 2, 'h_loss': 1, 'record_id': 15517, 'Start': 20763313}, {'g_type': 2, 'h_loss': 1, 'record_id': 15517, 'Start': 20763314}]

清单 B:

[{'in_data': '', 'espn': 'GJB2:NM_004004.5:exon2:c.C408A:p.Y136X', 's_id': 'CBK0944'}, {'in_data': '', 'espn': 'GJB2:NM_004004.5:exon2:c.G134A:p.G45E','s_id': 'CBK0945'}]

假设列表 A[0] 对应于列表 B[0] 等。

我怎样才能为列表中的每个字典做这样的事情?:

in_data = in_data + s_id + '(' + g_type + ', ' + h_loss + ')'

具有所需结果的列表 B:

[{'in_data': 'CBK0944(2, 1)', 'espn': 'GJB2:NM_004004.5:exon2:c.C408A:p.Y136X', 's_id': 'CBK0944'}, {'in_data': 'CBK0945(2, 1)', 'espn': 'GJB2:NM_004004.5:exon2:c.G134A:p.G45E','s_id': 'CBK0945'}]

标签: python

解决方案


代码:

List_A = [{'g_type': 2, 'h_loss': 1, 'record_id': 15517, 'Start': 20763313}, {'g_type': 2, 'h_loss': 1, 'record_id': 15517, 'Start': 20763314}]

List_B = [{'in_data': '', 'espn': 'GJB2:NM_004004.5:exon2:c.C408A:p.Y136X', 's_id': 'CBK0944'}, {'in_data': '', 'espn': 'GJB2:NM_004004.5:exon2:c.G134A:p.G45E','s_id': 'CBK0945'}]


for idx, item in enumerate(List_B):
    item['in_data'] += '{0}({1}, {2})'.format(item['s_id'],List_A[idx]['g_type'], List_A[idx]['h_loss'])

推荐阅读