Catherine Catherine - 4 months ago 18
Python Question

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?

Answer

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.

Comments