简体   繁体   English

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

[英]list of dict from existing list of dict in python

I am very new to Python and wondering some kind of solutions to the below issue.我对 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'}
               ]

I want to return a list of dictionary where the key is in ['Table', 'Data_Type', 'Column'] and value of Data_Type is the concatenated value of Data_Type and Column_Style .我想返回一个字典列表,其中键位于['Table', 'Data_Type', 'Column']并且Data_Type的值是Data_TypeColumn_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 will contain the output that you requested, assuming that original_list is the input list as you have provided it above. new_list将包含您请求的输出,假设original_list是您在上面提供的输入列表。

Actually you can use a generator function to generate a dict that match your criteria for each element in your original list of dict实际上,您可以使用生成器函数为原始 dict 列表中的每个元素生成与您的条件相匹配的 dict

def gen_dict(ori_dict_list):
    columns = ['Table', 'Data_Type', 'Column']
    for element in ori_dict_list:
        d = {}
        for field in columns:
            if field == 'Data_Type':
                if element['Column_Style'] is None:
                    d['Data_Type'] = element['Data_Type']
                else:
                    d['Data_Type'] = "{}({})".format(element['Data_Type'], element["Column_Style"])
            else:
                d[field] = element[field]
        yield d

Demo:演示:

>>> from pprint import pprint # Just to pretty print nothing special
>>> pprint(list(gen_dict(original_list)))
[{'Column': 'C1', 'Data_Type': 'int', 'Table': 'A'},
 {'Column': 'C2', 'Data_Type': 'varchar(20)', 'Table': 'A'},
 {'Column': 'C2', 'Data_Type': 'numeric(10,2)', 'Table': 'A'}]

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

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