简体   繁体   English

将一个字典列表的键和值添加到另一个字典列表

[英]Add key and value of one list of dictionaries to another list of dictionaries

I have two python lists of dictionaries.我有两个 Python 字典列表。

One is a keylist with multiple ids and date when updated.一个是具有多个 ID 和更新日期的密钥列表。

Other list is about persons, in list of persons there is person_id which corresponds with p_id in the keylist.其他列表是关于人员的,在人员列表中有与密钥列表中的 p_id 对应的 person_id。 I want to add the fam_id from keylist to persons dictionary.我想将密钥列表中的 fam_id 添加到人字典中。

keylist = [{'p_id':'001','fam_id':'FAM98','update':'2021-07-29'},
           {'p_id':'002','fam_id':'FAM1978','update':'2021-07-29'},
           {'p_id':'003','fam_id':'FAM1978','update':'2021-07-29'}]

persons = [{'person_id':'001','dob':'01-20-1997','mom_id':'34','color':'brown'},
           {'person_id':'002','dob':'12-05-2001','mom_id':'003', 'color':'black'},
           {'person_id':'003','dob':'01-02-1977','mom_id':'320', 'color':'brown'}]

I would like to get:我想得到:

persons = [{'person_id':'001','dob':'01-20-1997','mom_id':'34','color':'brown','fam_id':'FAM98'},
           {'person_id':'002','dob':'12-05-2001','mom_id':'003','color':'black','fam_id':'FAM1978'},
           {'person_id':'003','dob':'01-02-1977','mom_id':'320','color':'brown','fam_id':'FAM1978'}]

I don't know how to get this.我不知道如何得到这个。 What I tried was this (but I don't know how to get lcreate from keylist):我尝试的是这个(但我不知道如何从密钥列表中获取 lcreate ):

lcreate = {'001': 'FAM98', '002': 'FAM1978', '003': 'FAM1978'}
for dic in persons: dic["fam_id"] = lcreate[dic["person_id"]]

How can I get one dict(lcreate) from list of dict (keylist)?如何从 dict (keylist) 列表中获取一个 dict(lcreate)?

You can loop over both lists, and update persons dictionaries when those keys match.您可以遍历两个列表,并在这些键匹配时更新persons词典。

keylist=[{'p_id':'001','fam_id':'FAM98','update':'2021-07-29'},{'p_id':'002','fam_id':'FAM1978','update':'2021-07-29'},{'p_id':'003','fam_id':'FAM1978','update':'2021-07-29'}]
persons=[{'person_id':'001','dob':'01-20-1997','mom_id':'34', 'color':'brown'},{'person_id':'002','dob':'12-05-2001','mom_id':'003', 'color':'black'},{'person_id':'003','dob':'01-02-1977','mom_id':'320', 'color':'brown'}]
for x in persons:
    for y in keylist:
        if x['person_id'] == y['p_id']:
            x['fam_id'] = y['fam_id']

Result结果

>>> persons
[{'person_id': '001', 'dob': '01-20-1997', 'mom_id': '34', 'color': 'brown', 'fam_id': 'FAM98'},
 {'person_id': '002', 'dob': '12-05-2001', 'mom_id': '003', 'color': 'black', 'fam_id': 'FAM1978'},
 {'person_id': '003', 'dob': '01-02-1977', 'mom_id': '320', 'color': 'brown', 'fam_id': 'FAM1978'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM