[英]Python How to merge in a list of dicts content from another list of dicts dynamically
我对 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'}]
代码:
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'])
如果您想将这两个列表保留在其原始 state 中以供参考,您可以使用下面的列表理解重新创建一个新列表:
li_a = [{'g_type': 2, 'h_loss': 1, 'record_id': 15517, 'Start': 20763313}, {'g_type': 2, 'h_loss': 1, 'record_id': 15517, 'Start': 20763314}]
li_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'}]
merge = [{'in_data': '{}{}({},{})'.format(b['in_data'], b['s_id'], a['g_type'], a['h_loss']),
'espn':b['espn'],
's_id':b['s_id']
} for a,b in zip(li_a,li_b)]
merge
>> [{'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'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.