繁体   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