如何拼合字典中的值列表?

时间:2019-12-02 16:02:56

标签: python python-2.7 dictionary nested-lists flatten

我有一本这样的字典:

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

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

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

我该怎么做? 谢谢!

1 个答案:

答案 0 :(得分:-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']}