Skip to main content
 首页 » 编程设计

python之python中现有字典列表中的字典列表

2024年10月24日9jyk

我是 Python 的新手,想知道以下问题的某种解决方案。

original_list = [{'Table':'A', 'Column':'C1','Data_Type':'int','Column_Style':None, 'others':'O1'}, 
                 {'Table':'A', 'Column':'C2', 'Data_Type':'varchar','Column_Style': '20','others':'O2'}, 
                 {'Table':'A', 'Column':'C2', 'Data_Type':'numeric','Column_Style': '10,2','others':'O3'} 
               ] 

我想返回一个字典列表,其中键在 ['Table', 'Data_Type', 'Column'] 中,而 Data_Type 的值是串联的Data_Type 和 Column_Style 的值。

# expecting output like below 
new_list = [{'Table':'A', 'Column':'C1', 'Data_Type':'int'}, 
            {'Table':'A', 'Column':'C2', 'Data_Type':'varchar(20)'}, 
            {'Table':'A', 'Column':'C2', 'Data_Type':'numeric(10,2)'} 
           ] 

请您参考如下方法:

new_list = [] 
for innerDict in original_list: 
    newDict = {} 
    for key in innerDict: 
        if key not in ['Data_Type', 'Column_Style', 'others']: 
            newDict[key] = innerDict[key] 
        elif key == 'Data_Type': 
            if innerDict['Column_Style']: 
                newDict['Data_Type'] = innerDict['Data_Type'] + '(' + innerDict['Column_Style'] + ')' 
            else: 
                newDict['Data_Type'] = innerDict['Data_Type'] 
    new_list.append(newDict) 

new_list 将包含您请求的输出,假设 original_list 是您在上面提供的输入列表。