list: from 2 to 3 dimensions..looking for a nice way

Peter Otten __peter__ at web.de
Sat Nov 29 23:49:03 CET 2003


Peter Otten wrote:

> Peter Otten wrote:
> 
>> sven wrote:
>> 
>>> I've got a nested list->
>>> a = [[1,'house'],[2,'house'],[3,'garden']]
>>> 
>>> 
>>> and I want to get one level deeper  with the lists having the same value
>>> in index value 1
>>> 
>>> b =[[[1, 'house'], [2, 'house']], [[3, 'garten']]]

[...]

> Or rather
> 
> a = [[1,'house'],[2,'house'],[3,'garden']]
> 
> d  = {}
> for ns in a:
>     d.setdefault(ns[1], []).append(n)
> b = d.items()

So many errors in so few lines :-(
Hope I get it right this time:

a = [[1,'house'],[2,'house'],[3,'garden']]

d  = {}
for ns in a:
    d.setdefault(ns[1], []).append(ns)
b = d.values()

Peter





More information about the Python-list mailing list