简体   繁体   English

如何遍历字典列表,提取值并填写 python 中的另一个数据字典

[英]How to iterate through list of dictionary, extract values and fill in another data dictionary in python

I have a list of dictionary as below.我有一个字典列表如下。

[
    {'name':['mallesh'],'email':['m@gmail.com']},
    {'name':['bhavik'],'ssn':['1000011']},
    {'name':['jagarini'],'email':['m@gmail.com'],'phone':['111111']},
    {'name':['mallesh'],'email':['m@gmail.com'],'phone':['1234556'],'ssn':['10000012']}
]

I would like to extract the information from these dictionary based on keys, hold on its information in another dictionary as.我想根据键从这些字典中提取信息,将其信息保存在另一个字典中。

xml_master_dict={'name':[],'email':[],'phone':[],'ssn':[]}

Here xml_master_dict should be filled in with the respective key information as below.这里 xml_master_dict 应该填写相应的关键信息,如下所示。

In a fist dictionary we have this:在拳头字典中,我们有这个:

{'name':['mallesh'],'email':['m@gmail.com']}

In xml_master_dict name and email keys only will be updated with the current value, if any of key is not existed in the dictionary it should be filled in with None. xml_master_dict name 和 email 中的 key 只会更新为当前值,如果字典中不存在任何 key,则应填写 None。 in this case phone and ssn will be None在这种情况下 phone 和 ssn 将为 None

Here is an expected output:这是预期的 output:

{
 'name':['mallesh','bhavik','jagarini','mallesh'],
 'email':['m@gmail.com',None,'m@gmail.com','m@gmail.com'],
 'phone':[None,None,'111111','1234556'],
 'ssn':[None,'1000011',None,'10000012'],
}
pd.DataFrame({
 'name':['mallesh','bhavik','jagarini','mallesh'],
 'email':['m@gmail.com',None,'m@gmail.com','m@gmail.com'],
 'phone':[None,None,'111111','1234556'],
 'ssn':[None,'1000011',None,'10000012'],
})

在此处输入图像描述

You can define a function to get the first element of a dictionary value (or None if the key doesn't exist):您可以定义 function 以获取字典值的第一个元素(如果键不存在,则为None ):

def first_elem_of_value(record: dict, key: str):
    try:
        return record[key][0]
    except KeyError:
        return None

and then build the master dict with a single comprehension:然后用一个理解构建主字典:

xml_master_dict = {
    key: [
        first_elem_of_value(record, key)
        for record in data
    ]
    for key in ('name', 'email', 'phone', 'ssn')
}
>>> xml_master_dict
{'name': ['mallesh', 'bhavik', 'jagarini', 'mallesh'], 'email': ['m@gmail.com', None, 'm@gmail.com', 'm@gmail.com'], 'phone': [None, None, '111111', '1234556'], 'ssn': [None, '1000011', None, '10000012']}

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

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