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

问题描述 投票:0回答:1

我有这样的字典:

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

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

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

我该怎么做?谢谢!

python-2.7 dictionary nested-lists flatten
1个回答
0
投票

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

def flatten(l):
    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']}
© www.soinside.com 2019 - 2024. All rights reserved.