Best way to convert a list to a dictionary
Justin Sheehy
dworkin at ccs.neu.edu
Thu May 4 10:39:15 EDT 2000
Michael Husmann <michael.husmann at teleatlas.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
> 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:
Is your_list really what you described, a list where each element is
another list with two elements?
>>> your_list = [['a', 1], ['b', 2], ['c', 3]]
>>> d = {}
>>> for k, v in your_list:
... d[k] = v
...
>>> d
{'b': 2, 'c': 3, 'a': 1}
I suspect that your list was ill-formed.
-Justin
More information about the Python-list
mailing list