[Baypiggies] nested list to dict question
Jimmy Retzlaff
jimmy at retzlaff.com
Tue Dec 28 17:47:53 CET 2010
On Tue, Dec 28, 2010 at 7:51 AM, Vikram K <kpguy1975 at gmail.com> wrote:
> I have a nested list which looks something like this:
>
> x = [['104', '4501919'], ['104', '237681091'], ['104', '7669477'],
> ['100528064', '315259111']]
>
> I wish to convert this to a dict type which looks something like this:
>
> y = {'104': ['4501919', '237681091', '7669477'], '100528064': ['315259111']}
This is a great use for defaultdict (I haven't run this, there might
be a dumb error - but I've written it a gillion times):
from collections import defaultdict
y = defaultdict(list)
for k, v in x:
y[k].append(v)
See http://docs.python.org/library/collections.html#collections.defaultdict
- your example is almost exactly the same as the example in the docs.
Jimmy
----
Yelp is hiring - http://jobvite.com/m?3WAh0fwx
More information about the Baypiggies
mailing list