如何展平字典中的值列表?

How to flatten list of values in a dictionary?

提问人:LoC 提问时间:12/3/2019 最后编辑:ShadowRangerLoC 更新时间:12/3/2019 访问量:210

问:

我有一本这样的字典:

dic = {'a':[['1'],['4']],'b':['1'],'c':['2']}

我想删除不必要的列表以获得:

newdict={'a':['1','4'],'b':'1','c':'2'}

我该怎么做? 谢谢!

python python-2.7 字典 嵌套列表 扁平化

评论

0赞 Jaideep Shekhar 12/3/2019
是否保证列表的最大嵌套深度为 2?
0赞 LoC 12/3/2019
不,它可以比 2 高得多
0赞 ShadowRanger 12/3/2019
这回答了你的问题吗?展平不规则的列表列表。将其应用于你的方案只是对每个值调用其中一个配方(包装在调用中,当是生成器函数时)。flattenlistflattendict
1赞 ShadowRanger 12/3/2019
旁注:如果可能的话,请不要用 Python 2 编写新代码。它在不到一个月的时间内就完全停止了支持(2020 年 1 月 1 日是生命周期的结束),所以如果你想让你的技能/代码工作并能够使用新版本的 Python,而没有潜在的巨大的未修补的安全/稳定性错误,你真的应该以 Python 3 为目标。
1赞 ruohola 12/4/2019
@LoC 输入的正确输出是什么:?{'a':[[[['1'],['4']]],'3'],'b':['1'],'c':['2']}

答:

-1赞 Jaideep Shekhar 12/3/2019 #1

好吧,如果您不关心速度或效率,我想这可能会奏效:

def flatten(l):
    '''
    Function to flatten a list of any level into a single-level list

    PARAMETERS:
    -----------
        l: preferably a list to flatten, but will simply create a single element list for others

    RETURNS:
    --------
        output: list
    '''
    output = []
    for element in l:
        if type(element) == list:
            output.extend(flatten(element))
        else:
            output.append(element)
    return output

dic = {'a':[[[['1'],['4']]],'3'],'b':['1'],'c':['2']}
newdict = {key: flatten(value) for key, value in dic.items()}
print(newdict)

正如预期的那样,给出:

{'a': ['1', '4', '3'], 'b': ['1'], 'c': ['2']}

评论

0赞 LoC 12/3/2019
工作正常,谢谢!没有花时间运行我现在的工作,我会尝试在更大的词典上测试它。
0赞 ruohola 12/4/2019
@LoC 对于您的示例输入,这给出了不正确的输出。正确的输出是 。dic = {'a':[['1'],['4']],'b':['1'],'c':['2']}{'a': ['1', '4'], 'b': ['1'], 'c': ['2']}{'a': ['1', '4'], 'b': '1', 'c': '2'}