list to dict

Bart Nessux bart_nessux at hotmail.com
Wed Jun 16 13:11:03 EDT 2004


Josef Dalcolmo wrote:
> on Wed, 16 Jun 2004 09:29:23 -0400
> Bart Nessux <bart_nessux at hotmail.com> wrote:
> 
> 
>>What is the easiest/fastest way to build a dictionary from a list? The 
>>list contains 100,000 entries.
> 
> 
> The first question would be, what should the keys be? If the list consists of unique, unmutable items, then you might use the items themselves as key and write:
> 
> mydict = dict(zip(mylist, mylist))
> 
> obtaining a dictionary with all the keys and values identical (therefore somewhat of a waste, but occasionally useful). Note: if your original list did not contain unique values, you end up with a set.
> 
> If you want to remember the original order of the list, then write
> 
> mydict = dict(zip(mylist, xrange(len(mylist))))
> 
> 
> If you don't care about the key (that would be strange) then you can write:
> 
> mydict = dict(zip(xrange(len(mylist)), mylist))
> 
> Instead of len(mylist) you can also write 1000000 or any other number larger than your list.
>  
> 
> - Josef

Josef,

This was great. I understand how this works now. Thanks for such a 
broad, yet applicable explanation!

Bart



More information about the Python-list mailing list