首页 > 解决方案 > 具有嵌套列表值的字典到单个值列表

问题描述

我正在尝试为每个键在字典中创建单个值列表。贝娄是问题。我正在尝试在 Jinja 中解析列表,并且在使用模板之前将它们转换为一个看起来更好。

问题:

{'EFTPOS': [[10.0, 5.0], 15.0], 'StoreDeposit': [[5.0, 6.0], 11.0]}

结果:

{'EFTPOS': [10.0, 5.0, 15.0], 'StoreDeposit': [5.0, 6.0, 11.0]}

标签: python-3.x

解决方案


请尝试此代码片段。我已经定义了一种方法来删除嵌套列表并将其转换为平面列表。

output = []
def rmNest(ls): 
    for i in ls: 
        if type(i) == list: 
            rmNest(i) 
        else: 
            output.append(i)
    return output


a_dict = {'EFTPOS': [[10.0, 5.0], 15.0], 'StoreDeposit': [[5.0, 6.0], 11.0]}

new_dict = {}

for i in a_dict:
    new_dict[i] = rmNest(a_dict[i])
    output = []

推荐阅读