简体   繁体   中英

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.

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 .

# 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.

Actually you can use a generator function to generate a dict that match your criteria for each element in your original list of 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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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