提问人:LoC 提问时间:12/3/2019 最后编辑:ShadowRangerLoC 更新时间:12/3/2019 访问量:210
如何展平字典中的值列表?
How to flatten list of values in a dictionary?
问:
我有一本这样的字典:
dic = {'a':[['1'],['4']],'b':['1'],'c':['2']}
我想删除不必要的列表以获得:
newdict={'a':['1','4'],'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'}
评论
flatten
list
flatten
dict
{'a':[[[['1'],['4']]],'3'],'b':['1'],'c':['2']}