list 2 dict?

Rob Williscroft rtw at rtw.me.uk
Sun Jan 2 08:56:06 EST 2011


Octavian Rasnita wrote in news:0DB6C288B2274DBBA5463E7771349EFB at 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.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /