2016-07-26 136 views
1

我想列出的清單轉換成一個嵌套的字典:轉換列表的列表到嵌套字典

我的代碼:

csv_data={} 
    for key, value in csv_files.iteritems(): 
     if key in desired_keys: 
      csv_data[key]=[] 

      for element in value: 
       csv_data[key].append(element[1:]) 

此代碼給我下面的:

{ 'Network': [ 
     ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], 
     ['0.3', '0.1', '0.3'] 
    ], 
    'CPU': [ 
     ['Processor Time', 'User Time', 'Privileged Time'], 
     ['13.8', '6.7', '7.2'] 
    ] 
} 

因此,在這種情況下,每個「值」是含有兩個列表的列表,containung一個「標題」列表和「數值」列表

不過我想產生這樣的格式:

{ 'Network': { 
     'Total KB/sec':0.3, 
     'Sent KB/sec':0.1, 
     'Received KB/sec':0.3 
    }, 
    'CPU': { 
     'Processor Time':'13.8', 
     'User Time': '6.7', 
     'Privileged Time': '7.2' 
    } 
} 

我應該如何改變我的代碼,以產生這種輸出?

回答

4

假設我演示使用的zip()對你的鑰匙之一,Network

>>> network = [ 
    ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], 
    ['0.3', '0.1', '0.3'] 
] 

zip()荷蘭國際集團的兩個名單將產生一組可以變成一個字典,通過簡單地調用dict()元組它。換句話說,

>>> dict(zip(network[0], network[1])) 
{'Received KB/sec': '0.3', 'Sent KB/sec': '0.1', 'Total KB/sec': '0.3'} 

重複您的CPU鍵。

+1

我會離開o我在這裏寫了一行,可能對OP有用,而不是浪費。 'csv_data [key] = dict(zip(*(row [1:] in value in value)))''' –

0

方法不zip

dct = { 'Network': [ 
     ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], 
     ['0.3', '0.1', '0.3'] 
    ], 
    'CPU': [ 
     ['Processor Time', 'User Time', 'Privileged Time'], 
     ['13.8', '6.7', '7.2'] 
    ] 
} 

for key, val in dct.items(): 
    placeholder_dct= {} 
    for i in range(len(val[0])): 
     placeholder_dct[val[0][i]] = val[1][i] 
    dct[key] = placeholder_dct 

print(dct) 
2

zip()是非常方便的同時迭代列表,並轉換到字典變得非常容易dict()

def to_dict(dic): 
    for key, value in dic.iteritems(): 
     dic[key] = dict(zip(* value)) 
    return dic 

輸出示例:

d = {'Network': [['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], 
['0.3', '0.1', '0.3']], 
'CPU': [['Processor Time', 'User Time', 'Privileged Time'], 
['13.8', 6.7', '7.2']]} 

print to_dict(d) 
>>> {'Network': {'Sent KB/sec': '0.1', 'Total KB/sec': '0.3', 'Received 
KB/sec': '0.3'}, 'CPU': {'Processor Time': '13.8', 'Privileged Time': 
'7.2', 'User Time': '6.7'}} 

它是如何工作的?

當使用拉鍊功能上列出它由在其各自耦合每個橫跨列表中的列表元素的返回元組對並迭代各級列表將它們視爲平行的列表的列表索引。因此,如果我們孤立zip(* value)操作,我們可以清楚地看到操作的結果:

>>> [('Total KB/sec', '0.3'), ('Sent KB/sec', '0.1'), ('Received 
    KB/sec', '0.3')] 
    [('Processor Time', '13.8'), ('User Time', '6.7'), ('Privileged 
    Time', '7.2')] 
0

試試這個代碼:

{x:{z:t for z,t in (dict(zip(y[0], y[1]))).items()} for x,y in data.items()} 

當輸入:

data={ 'Network': [ 
    ['Total KB/sec', 'Sent KB/sec', 'Received KB/sec'], 
    ['0.3', '0.1', '0.3'] 
], 
'CPU': [ 
    ['Processor Time', 'User Time', 'Privileged Time'], 
    ['13.8', '6.7', '7.2'] 
]} 

輸出:

res= {'Network': {'Sent KB/sec': '0.1', 'Total KB/sec': '0.3', 'Received KB/sec': '0.3'}, 'CPU': {'Processor Time': '13.8', 'Privileged Time': '7.2', 'User Time': '6.7'}}