Best way to convert a list to a dictionary

Michael Husmann michael.husmann at teleatlas.com
Thu May 4 01:53:59 EDT 2000


Justin Sheehy wrote:

> "Lars Lundstedt" <lars.lundstedt at telia.com> writes:
>
> > I have a list where each element is another list with two elements.
> > What is the best way to convert this to a dictionary?
>
> Something like this would probably be simplest:
>
> d = {}
> for k, v in your_list:
>     d[k] = v
>
> -Justin
>
>

d = {}
for k, v in your_list:
    d[k] = v

This example looks nice bus does not work with my Python 1.52. Trying to
get both elements from 'your_list' produces a TypeError exception:

Traceback (innermost last):
  File "<pyshell#10>", line 1, in ?
    for (k,v) in l:
TypeError: unpack non-sequence


- Michael




More information about the Python-list mailing list