On Tue, May 17, 2011 at 11:30 AM, Emile van Sebille <em...@fenx.com> wrote:
> 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 > > _______________________________________________ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for the quick response Emile! However, this only seems to solve part of the problem. It seems to set up a single key value dictionary (e.g. {'server1' : ['state=active', 'ncpu=8']}, etc.)I'm looking for more of a multi-way dictionary to be able to access down different paths such as: mymem = node['server1']['mem'] myncpu = node['server1']['ncpu'] I want to be able to change the list part of the example you provided into a sub-dictionary similar to (preferably done directly from the original data): { 'server1' : { 'state' : 'active', 'ncpu' : 8}, 'server2' : {'state' : 'active', 'ncpu' : 32}}
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor