簡體   English   中英

將列表列表轉換為嵌套字典

[英]Convert a list of lists into a nested dictionary

我正在嘗試將列表列表轉換為嵌套字典:

我的代碼:

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']
    ]
}

因此,在這種情況下,每個“值”都是一個包含兩個列表的列表,其中包含一個“標題”列表和一個“數值”列表

但是我想產生一種像這樣的格式:

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

我應該如何更改代碼以產生此輸出?

假設我在您的其中一個鍵Network上演示了zip()的用法:

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

zip()這兩個列表將產生一組元組,只需將其調用dict()就可以將其轉換為dict。 換一種說法,

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

重復輸入您的CPU密鑰。

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函數時,它會返回一個元組對列表, 通過耦合跨越每個列表元素在其各自索引處的每個列表元素來迭代列表的各個級別,將它們視為並行列表 因此,如果我們隔離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')]

不用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)

試試這個代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM