2015-11-04 51 views
-2

假設我有這個名單使用詞典:Python列表,以不同的密鑰

In [5]: m 

Out[5]: [{0: ['a', 'b'], 1: '1', 2: '2'}, 
     {0: ['a', 'b'], 1: '3', 2: '4'}, 
     {0: ['xx', 'yy'], 1: '100', 2: '200'}, 
     {0: ['xx', 'yy'], 1: '300', 2: '400'}] 

我這樣做:

In [6]: r = defaultdict(list) 

In [7]: for k, v in ((k, v) for row in m for k, v in row.iteritems()): 
      r[k].append(v) 

並返回:

In [8]: r 
Out[8]: defaultdict(list, 
     {0: [['a', 'b'], ['a', 'b'], ['xx', 'yy'], ['xx', 'yy']], 
     1: ['1', '3', '100', '300'], 
     2: ['2', '4', '200', '400']}) 

但我想要其他的東西,像這樣:

 {0: ['a', 'b'], 
     1: ['1', '3'], 
     2: ['2', '4']}, 

     {0: ['xx', 'yy'], 
     1: ['100', '300'], 
     2: ['200', '400']} 

我該怎麼做?我想在關鍵字0中取相同的值,並收集其他所有在其他關鍵字中找到的值。

非常感謝!

+1

我不明白你要做的轉換。你能一步一步地描述如何從你擁有的東西開始,最終得到你想要的東西嗎?它不僅可能讓你獲得更好的幫助,甚至可以「點擊」如何自己做。 –

+0

只將初始列表視爲兩個單獨的列表。你會沒事的。 – sobolevn

+0

@sobolevn我不能對待初始列表,因爲這是合成數據,對於設置的一種方式,真正的列表有很多鍵,我不能手動完成。 –

回答

1

第1步 - 先拆分詞典,否則,不清楚自動拆分它們的邏輯是什麼。 第2步 - 遍歷字典列表並應用一些if語句。 這是我認爲它應該看起來像。希望我有這個背後的邏輯吧:

d = [{0: ['1', '2'], 1: '3', 2: '4'}, 
    {0: ['1', '2'], 1: '6', 2: '7'}, 
    {0: ['1111', '2222'], 1: '6', 2: '7'}, 
    {0: ['1111', '2222'], 1: '66', 2: '77'} 
    ] 

    #step 1 
    def splitList(l, n): 
     """ 
     takes list and positions to take from the list  
     """ 
     output = [] 
     for p in n: 
      output.append(l[p]) 
     return output 

    #step 2 
    def orgDict(d): 
     """ 
     modifies list of dictionaries into 1 
     """ 
     d_output = {}  
     for d_ind in d:     
      for d_ind2 in d_ind: 
       if (d_output.get(d_ind2) == None): 
        if (type(d_ind[d_ind2]) == list): 
         d_output[d_ind2] = d_ind[d_ind2] 
        else: 
         d_output[d_ind2] = [d_ind[d_ind2]] 
       else: 
        if ((d_ind[d_ind2] not in d_output[d_ind2]) and (d_ind[d_ind2] != d_output[d_ind2])): 
         d_output[d_ind2].append(d_ind[d_ind2]) 
     return d_output 

#tests 
#expected output: 
#{0: ['1', '2'], 1: ['3', '6'], 2: ['4', '7']} 
print orgDict(splitList(d,[0,1])) 

#expected output: 
#{0: ['1111', '2222'], 1: ['6', '66'], 2: ['7', '77']} 
print orgDict(splitList(d,[2,3]))