简体   繁体   中英

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 = [
    ['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. 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.

zip() comes in very handy for iterating the lists at the same time, and converting to a dictionary becomes very easy with 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. So if we isolate the zip(* value) operation we can clearly see the result of the operation:

>>> [('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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM