【问题标题】:How to get list of dict instead of using collection.defaultdict in python如何获取dict列表而不是在python中使用collection.defaultdict
【发布时间】:2014-09-16 01:58:44
【问题描述】:

我正在尝试将列表递归地转换为嵌套字典,如下所示:-

给定输入:-

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。

【问题讨论】:

  • ARGH!!! 你为什么直接打电话给__setitem__?!?此外,您的代码实际上并不需要defaultdict,因为您只需要并且始终创建一个密钥。
  • 非常感谢@Bakuriu 的回复。这里我使用 setitem 因为下一个条目 ['childs'] 也是一个字典列表。它是最简单的模型,因为我需要将孩子用于不同级别的多个条目以进一步发展。有没有其他方法请建议。
  • 我的意思是new_class_dict.__setitem__('name', listitem)完全等同于new_class_dict['name'] = listitem。实际上它更慢,因为它需要额外的方法查找。如果你曾直接调用名称中带有双下划线的方法你做错了(有一些例外,但不适合初学者)。
  • 感谢@Bakuriu,我从其他关于堆栈溢出的帖子中学到了这种风格。但是非常感谢这个解释。我会记住这一点。

标签: python recursion dictionary yaml


【解决方案1】:

这样就可以实现了

parse_list = ['A','B','C','D']

dicton={}

for i in reversed(parse_list):
    dicton['child']=[dicton]
    dicton['name']=i


print dicton
#output {'name': 'A', 
         'child': [{'name': 'B', 
                     'child': [{'name': 'C', 
                                'child': [{'name': 'D', 
                                            'child': [{}]
                                                         }]}]}]}

【讨论】:

  • 请注意,如果性能很重要,则应首选递归答案,因为在这里您将在每个步骤中重新创建 dict。否则,很好的解决方案!
  • @SébastienDeprez 我想知道你能不能解释一下。所以我会学习
  • 使用dict(dicton),您将在新字典中复制dicton 的所有内容。
  • @SébastienDeprez 这会导致任何副作用吗?
  • 不,一切都很好!我只是注意到了性能问题。
【解决方案2】:

以递归方式

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())

【讨论】:

  • 哦还没有看到其他答案...所以可能是另一种解决方案
  • 谢谢,但是当我尝试这段代码时,我得到了以下输出:- {'childs': {'childs': [{...}], 'name': 'B'}, '名称':'A'} 。在 [{...}] 内,它重复地包含 B 的下一个字典。
  • 哦,有一个小错误 :) 抱歉
  • 现在还有一个小错误 resultDict = createdict(parse_list) 而不是 resultDict = createdict(parse_list, dict()) 。但这就是我正在寻找的递归使用。非常感谢...
【解决方案3】:

这是一个递归解决方案

parse_list = ['A','B','C','D']

def descend(l):
    if l:
        return [{'name': l[0],
                'childs': descend(l[1:])}]
    else:
        return None

data = descend(parse_list)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2013-02-18
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多