0

以下のデータで困っています。

リストがあります。

[{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'}

助けてください。

4

2 に答える 2

0

さて、厳密にソートされた文字列のリストをdictに変換する方法の@lazyrの回答から取得しましたか? .

次に、文字列に変換し、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とみんなが私を助けてくれました。磨きが必要です。

于 2012-08-23T18:39:36.080 に答える
0

lazyr が言ったように、そのようなキーを複製することはできませんdict。次のような形式に変換して、有効な Pythondict構文にすることができます。

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

リストの最後のレコードのみを取得する理由は、辞書が一意のキーを使用しているためです

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
于 2012-08-23T10:59:23.690 に答える