2013-03-18 38 views
0

給予名單上有字典清單如下圖所示:如何使字典從字典

targer = [ 
    {"id":1,"search":"xyz"}, 
    {"id":2,"children":[ 
     {"id":3,"search":'xyz'}, 
     {"id":4,"search":'xyz'}, 
     {"id":5,"children":[ 
      {"id":6,"search":'xyz'}, 
      {"id":7,"search":'xyz'}, 
      {"id":8,"search":'xyz'}]}, 
     {"id":9,"search":'xyz'}, 
     {"id":10,"search":'xyz'}]}, 
    {"id":11},{"id":12}] 

現在我要讓詞典列表如下圖所示,從目標列表:

output = [ 
    {'tier1': 1, 'searchterm': 'xyz'}, 
    {'tier1': 2, 'tier2': 3,'searchterm': 'xyz'}, 
    {'tier1': 2,'tier2': 4,'searchterm': 'xyz'}, 
    {'tier1': 2, 'tier2': 5,'tier3': 6,'searchterm': 'xyz'}, 
    {'tier1': 2, 'tier2': 5,'tier3': 7,'searchterm': 'xyz'}, 
    {'tier1': 2, 'tier2': 5,'tier3': 8, 'searchterm': 'xyz'}, 
    {'tier1': 2, 'tier2': 9,'searchterm': 'xyz'}, 
    {'tier1': 2, 'tier2': 10,'searchterm': 'xyz'}, 
    {'tier1': 11, 'searchterm': 'xyz'}, 
    {'tier1': 12, 'searchterm': 'xyz'}] 

我嘗試了一些步驟: 1.首先我在轉變目標列表中列出如下圖所示:

mylist = [ 
    [1, 'xyz'], 
    [2, 3, 'xyz'], 
    [2, 4, 'xyz'], 
    [2, 5, 6, 'xyz'], 
    [2, 5, 7, 'xyz'], 
    [2, 5, 8, 'xyz'], 
    [2, 9, 'xyz'], 
    [2, 10, 'xyz'], 
    [11], 
    [12]] 

2.然後我採用下面的代碼上MYLIST得到輸出:

for i in lis: 
dic={} 


length=len(i) 
if length==2: 

    dic['tier1']=i[0] 
    dic['searchterm']=i[1] 

if length==3: 
    dic['tier1']=i[0] 
    dic['tier2']=i[1] 
    dic['searchterm']=i[2] 

if length==4: 
    dic['tier1']=i[0] 
    dic['tier2']=i[1] 
    dic['tier3']=i[2] 
    dic['searchterm']=i[3] 

if length==5: 
    dic['tier1']=i[0] 
    dic['tier2']=i[1] 
    dic['tier3']=i[2] 
    dic['tier4']=i[3] 
    dic['searchterm']=i[4] 

if length==6: 
    dic['tier1']=i[0] 
    dic['tier2']=i[1] 
    dic['tier3']=i[2] 
    dic['tier4']=i[3] 
    dic['tier5']=i[4] 
    dic['searchterm']=i[5] 

target.append(dic) 

但我想從出應用上面的步驟直接目標列表輸出。 請幫忙解決這個問題。

+4

提示:嘗試遞歸 – 2013-03-18 06:49:58

+0

爲什麼是'等級1的'searchterm'值:11'和'等級1:12' 「XYZ」?在原始數據結構中,這些字典沒有「搜索」鍵。 – 2013-03-18 21:05:17

回答

1

遞歸發生器將這樣的伎倆:

def flatten(list_of_dicts, tier = 1, prev = {}): 

    for item in list_of_dicts: 
     curr = prev.copy() 
     curr['tier%d' %tier] = item['id'] 
     if 'children' in item: 
      for next in flatten(item['children'], tier + 1, curr): 
       yield next 
     else: 
      if 'search' in item: #some items don't have it 
       curr['searchterm'] = item['search'] 
      yield curr 


>>> list(flatten(targer)) 
[{'tier1': 1, 'searchterm': 'xyz'}, {'tier1': 2, 'searchterm': 'xyz', 'tier2': 3}, {'tier1': 2, 'searchterm': 'xyz', 'tier2': 4}, {'tier1': 2, 'searchterm': 'xyz', 'tier3': 6, 'tier2': 5}, {'tier1': 2, 'searchterm': 'xyz', 'tier3': 7, 'tier2': 5}, {'tier1': 2, 'searchterm': 'xyz', 'tier3': 8, 'tier2': 5}, {'tier1': 2, 'searchterm': 'xyz', 'tier2': 9}, {'tier1': 2, 'searchterm': 'xyz', 'tier2': 10}, {'tier1': 11}, {'tier1': 12}]