Octavian Rasnita wrote in news:0db6c288b2274dbba5463e7771349...@teddy in gmane.comp.python.general:
> Hi, > > If I want to create a dictionary from a list, is there a better way > than the long line below? > > l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b'] > > d = dict(zip([l[x] for x in range(len(l)) if x %2 == 0], [l[x] for x > in range(len(l)) if x %2 == 1])) > > print(d) > > {8: 'b', 1: 2, 3: 4, 5: 6, 7: 'a'} >>> dict( zip( l[ :: 2 ], l[ 1 :: 2 ] ) ) {8: 'b', 1: 2, 3: 4, 5: 6, 7: 'a'} If you don't know about slice notation, the synatax I'm using above is: list[ start : stop : step ] where I have ommited the "stop" item, which defaults to the length of the list. <http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode- list-tuple-bytearray-buffer-xrange> That will make 3 lists before it makes the dict thought, so if the list is large: >>> dict( ( l[ i ], l[ i + 1 ] ) for i in xrange( 0, len( l ), 2 ) ) may be better. Rob. -- http://mail.python.org/mailman/listinfo/python-list