simple question on list manipulation from a newbie

Sengly Sengly.Heng at gmail.com
Sun Jun 8 08:42:48 CEST 2008


On Jun 8, 6:38 am, Sam Denton <stden... at sbcglobal.net> wrote:
> Sengly wrote:
> > Dear all,
>
> > I am working with wordnet and I am a python newbie. I'd like to know
> > how can I transfer a list below
>
> > In [69]: dog
> > Out[69]:
> > [{noun: dog, domestic_dog, Canis_familiaris},
> >  {noun: frump, dog},
> >  {noun: dog},
> >  {noun: cad, bounder, blackguard, dog, hound, heel},
> >  {noun: frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst,
> > weenie},
> >  {noun: pawl, detent, click, dog},
> >  {noun: andiron, firedog, dog, dog-iron}]
>
> > to a list like this with python:
>
> > [dog, domestic_dog, Canis_familiaris,
> > frump, dog,
> > dog,
> > cad, bounder, blackguard, dog, hound, heel,
> > frank, frankfurter, hotdog, hot_dog, dog, wiener, wienerwurst,
> > weenie},
> > pawl, detent, click, dog},
> > andiron, firedog, dog, dog-iron]
>
> I can't help you with the formatting, but here's a solution using Python
> data structures:
>
>  >>> alist = [
>      {'noun': ('dog', 'domestic_dog', 'Canis_familiaris')},
>      {'noun': ('frump', 'dog')},
>      {'noun': ('dog',)},
>      {'noun': ('cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel')},
>      {'noun': ('frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog',
> 'wiener', 'wienerwurst', 'weenie')},
>      {'noun': ('pawl', 'detent', 'click', 'dog')},
>      {'noun': ('andiron', 'firedog', 'dog', 'dog-iron')},
>      ]
>
>  >>> merged = {}
>  >>> for d in alist:
>          for key, value in d.iteritems():
>              merged.setdefault(key, []).extend(value)
>
>  >>> merged
> {'noun': ['dog', 'domestic_dog', 'Canis_familiaris', 'frump', 'dog',
> 'dog', 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel', 'frank',
> 'frankfurter', 'hotdog', 'hot_dog', 'dog', 'wiener', 'wienerwurst',
> 'weenie', 'pawl', 'detent', 'click', 'dog', 'andiron', 'firedog', 'dog',
> 'dog-iron']}

Thank you all for your help. I found a solution as the following:

alist = [
     {'noun': 'dog', 'domestic_dog', 'Canis_familiaris'},
     {'noun': 'frump', 'dog'},
     {'noun': 'dog',},
     {'noun': 'cad', 'bounder', 'blackguard', 'dog', 'hound', 'heel'},
     {'noun': 'frank', 'frankfurter', 'hotdog', 'hot_dog', 'dog',
'wiener', 'wienerwurst', 'weenie'},
     {'noun': 'pawl', 'detent', 'click', 'dog'},
     {'noun': 'andiron', 'firedog', 'dog', 'dog-iron'},
     ]

def getAll(alist):
	list=[]
	for i in range(0,len(alist)):
		list.extend(alist[i][:])
	return list

Kind regards,

Sengly



More information about the Python-list mailing list