本文介绍了如何获取字典列表而不是在python中使用collection.defaultdict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正尝试将列表递归转换为嵌套字典,如下所示:-
I am trying to convert a list into nested dictionaries recursively as following :-
输入:-
parse_list = ['A','B','C','D']
必需的输出:-
data = [
{'name': 'A',
'childs': [
{'name': 'B',
'childs': [
{'name': 'C',
'childs': [
{'name': 'D',
'childs': none }]}]}]}]
我的代码:-
from collections import defaultdict
class_dict =defaultdict(list)
data =defaultdict(list)
parse_list.reverse()
def create_dict(parse_list,class_dict):
for index ,listitem in enumerate(parse_list):
new_class_dict = defaultdict(list)
new_class_dict.__setitem__('name', listitem)
new_class_dict['childs'].append(class_dict)
class_dict = new_class_dict
return class_dict
data = create_dict(parse_list,class_dict)
import yaml
with open('data.yml', 'w') as outfile:
outfile.write( yaml.dump(data, default_flow_style=False))
但是由于defaultdict(list),我总是在yaml中获得许多额外的缩进,这是不期望的.还有其他方法可以获取[{....}]而不是使用collection.defaultdict.
However because of defaultdict(list), I always get many extra indent in yaml, which are not expected. Is there any other way to get the [{....}] instead of using collection.defaultdict.
推荐答案
以递归方式
parse_list = ['A','B','C','D']
def createdict(l, d):
if len(l) == 0:
return None
d = dict()
d['name'] = l[0]
d['childs'] = [createdict(l[1:], d)]
return d
resultDict = createdict(parse_list, dict())
这篇关于如何获取字典列表而不是在python中使用collection.defaultdict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!