list 2 dict?
Octavian Rasnita
orasnita at gmail.com
Sun Jan 2 10:09:38 EST 2011
From: "Rob Williscroft" <rtw at rtw.me.uk>
> 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.
Thank you all.
I have also discovered that I can zip 2 lists made with range(0, len(l), 2) and range(1, len(l), 2) but I remembered about that the slice notation accepts that third argument and as Stefan suggested, looks to be a shorter way.
I have first thought to the solution you suggested, but I have forgotten to create a tuple from the pair of elements so it didn't work.
I wasn't thinking to performance, but yes, it may be important for large lists.
It seems that in some cases there are more ways to do it in Python than in Perl. :-)
Octavian
More information about the Python-list
mailing list