【问题标题】:Tree style dictionary树样式字典
【发布时间】:2012-08-23 10:32:49
【问题描述】:

我被以下数据困住了。

有一个清单。

[{name: '/', children: [{name: 'bin'}, {name: 'sbin'}, {name: 'home'}]},
{name: 'home', children: [{name: 'user1'}, {name: 'user2'}]},
{name: 'user2', children: [{name: 'desktop'}]}]

我想把上面的列表转换成下面的字典。

{name: '/', children: [{name: '/bin'}, {name: '/sbin'}, {name: '/home', children: [{name: 'user1'}, {name: 'user2', children: [{name: 'desktop'}]}]}]}

我写了一些代码来转换上述样式的数据。

def recT(data, child, parent, collector):
    dparent = dict(name=parent)
    dchildren = dict()
    lst = []
    for c in child:
        lst.append(dict(name=c['name']))
        for d in data:
            if c['name'] == d['name']:
                if len(d) > 1:
                    dchildren.update(dict(children=recT(data, d['children'], d['name'], collector)))
    dparent.update(dchildren)
    collector.update(dparent)
    return lst

那么,

myd = dict()
for d in data2:
    if len(d) > 1:
        recT(data2, d['children'], d['name'], myd)

注意:data2 是我要转换的字典列表。

但是,输出字典是列表中的最后一条记录:

{'children': [{'name': 'desktop'}], 'name': 'user2'}

请帮忙。

【问题讨论】:

  • 向我们展示您的代码,以便我们提供帮助 ...
  • 我希望你意识到列表数据结构不能处理树中任何地方的两个同名目录(例如 /bin 和 /usr/bin)。

标签: python list dictionary tree


【解决方案1】:

正如lazr 所说,您不能像那样在dict 中复制密钥。您可以将其转换为如下格式以成为有效的 python dict 语法:

{
  '/': {
    'bin': {}, 
    'sbin': {}, 
    'home': {
      'user1': {},
      'user2': {
        'desktop': {}
      }
  }
}

您只获得列表中最后一条记录的原因是您的 dict 使用唯一键

mydict = {}
mydict['name'] = 1
mydict['name'] # is 1
mydict['name'] = 2

for x,y in mydict.iteritems():
  print '{0}: {1}'.format(x,y)
>> name: 2 # Note only one entry

【讨论】:

    【解决方案2】:

    现在,我是从@lazyr 对How to convert a strictly sorted list of strings into dict? 的回答中得到的。

    然后,我将其转换为字符串并使用 myReplacer() 将其更改为想要的格式。

    这里:

    def myReplacer(strdata):
        strdata = strdata.replace("{", '{ name:')
        strdata = strdata.replace(': {', ', children : [{')
        strdata = strdata.replace('}', '}]')
        strdata = strdata.replace(': None,', '},{ name:')
        strdata = strdata.replace(': None', '')
        strdata = strdata.replace(", '", "}, { name: '")
        return strdata[:-1]
    

    感谢@lazyr,每个人都帮助了我。它需要一些润色。

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 2011-11-24
      相关资源
      最近更新 更多