将列表列表转换为嵌套字典

时间:2016-07-26 14:23:18

标签: python list dictionary

我正在尝试将列表列表转换为嵌套字典:

我的代码:

PXXXXX

此代码给出了以下内容:

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

如何更改代码以生成此输出?

4 个答案:

答案 0 :(得分:4)

假设我在您的某个密钥zip()上展示Network的使用:

>>> 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键。

答案 1 :(得分: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函数时,它会返回元组对的列表,并通过耦合每个列表来迭代各种级别的列表,将它们视为并列列表元素跨越各自索引的列表。因此,如果我们隔离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')]

答案 2 :(得分: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)

答案 3 :(得分: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'}}