[Tutor] how to convert list of lists to dict

Emile van Sebille emile at fenx.com
Tue May 17 18:30:25 CEST 2011


On 5/17/2011 8:58 AM Brad Hudson said...
> I'm new to python and have a need to convert a 'list of lists' to a
> dictionary object. Can someone help me to convert data similar to the
> following using two different examples of a list comprehension and a for
> loop?
>
> Data is similar to the following:
> [['name=server1', 'state=active', 'ncpu=8', 'mem=8589934592',
> 'uptime=5784399'], ['name=server2', 'state=active', 'ncpu=32',
> 'mem=34359738368', 'uptime=5416796'], ['name=server3', 'state=inactive',
> 'ncpu=8', 'mem=8589934592', 'uptime=']]
>
> I'd like to convert the list data into a dictionary similar to the
> following:
> node['server1'] = {'state' : 'active', 'ncpu' : 8, 'mem' : 8589934592,
> 'uptime' : 5784399}
> node['server2'] = {'state' : 'active', 'ncpu' : 32, 'mem' : 34359738368,
> 'uptime' : 5416796}
> node['server3'] = {'state' : 'inactive', 'ncpu' : 8, 'mem' : 8589934592,
> 'uptime' : None}
>
> This would allow me to access information like:
> node['server1']['mem']
>

You'll want to use dict,

dict([jj[0].split("=")[1],jj[1:]] for jj in LofL)

Emile



More information about the Tutor mailing list