python - python 中现有 dict 列表中的 dict 列表

标签 python python-3.x

我对 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_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 将包含您请求的输出,假设 original_list 是您在上面提供的输入列表。

关于python - python 中现有 dict 列表中的 dict 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36313853/

相关文章:

python 使用 *args 和 **kwargs 以及其他位置参数和仅关键字参数解包 arg 列表

python-3.x - 如何使用 fastapi 日志记录捕获 X-Forwarded-For?

python - 如何获取当前的 'package' 名称? (设置.py)

python-3.x - Kivy:已弃用功能的替代方案

python - 使用正则表达式提取两个字符串之间的字符串

python模块层次结构命名约定

python - 下载文件之前如何从链接获取文件名?

python - 使用 Python 3 将 Arcade 中的窗口居中

python - 如何将异步生成器合并到 python 3.5+ 中的普通生成器中

python - 如何修复 "No module named ' kivy._clock'"ubuntu 中的错误?