简体   繁体   English

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

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

I am trying to convert a list of lists into a nested dictionary: 我正在尝试将列表列表转换为嵌套字典:

My code: 我的代码:

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:])

This code gives me the following: 这段代码为我提供了以下内容:

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

So in this case each "value" is a list containing two lists, containung a "title" list and a "numerical value" list 因此,在这种情况下,每个“值”都是一个包含两个列表的列表,其中包含一个“标题”列表和一个“数值”列表

However I want to produce a format like: 但是我想产生一种像这样的格式:

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

How should I change my code to produce this output? 我应该如何更改代码以产生此输出?

Suppose I demonstrate the use of zip() on one of your keys, Network : 假设我在您的其中一个键Network上演示了zip()的用法:

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

zip() ing the two lists will yield a set of tuples that can be turned into a dict, by simply calling dict() on it. zip()这两个列表将产生一组元组,只需将其调用dict()就可以将其转换为dict。 In other words, 换一种说法,

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

Repeat for your CPU key. 重复输入您的CPU密钥。

zip() comes in very handy for iterating the lists at the same time, and converting to a dictionary becomes very easy with dict() . zip()可以很方便地同时迭代列表,而使用dict()转换为字典变得非常容易。

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

Sample output: 样本输出:

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

How does it work? 它是如何工作的?

When you use the zip function on lists it returns a list of tuple pairs and iterates the various levels of lists treating them as parallel lists by coupling each of the lists elements spanning the lists at their respective index. 当您在列表上使用zip函数时,它会返回一个元组对列表, 通过耦合跨越每个列表元素在其各自索引处的每个列表元素来迭代列表的各个级别,将它们视为并行列表 So if we isolate the zip(* value) operation we can clearly see the result of the operation: 因此,如果我们隔离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')]

Approach without zip 不用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)

Try this code : 试试这个代码:

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

When Input : 输入时:

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

Output : 输出:

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