Rebuild list of objects with redundancies on objects' attribute

Nico Grubert nicogrubert at gmail.com
Thu Jan 10 05:23:20 EST 2008


Hi there

I have a list of dummy objects which have the attributes 'location', 
'name', 'gender'.
Now I want to rebuild this list in order to avoid redundancies on 
objects with the same 'location'.

Example:

#------------------------------------------------------------------
class Dummy:
     pass

a = Dummy()
a.location = 'tokio'
a.name = 'john'
a.gender = 'm'

b = Dummy()
b.location = 'tokio'
b.name = 'peter'
b.gender = 'm'

c = Dummy()
c.location = 'madrid'
c.name = 'susan'
c.gender = 'f'

d = Dummy()
d.location = 'london'
d.name = 'alex'
d.gender = 'm'

persons = [a, b, c, d]

print "loc     name   gender"
print "---------------------"
for obj in persons:
     print "%s - %s - %s" % (obj.location, obj.name, obj.gender)

#------------------------------------------------------------------

The output reads like this:

   loc     name   gender
   ---------------------
   tokio   john   m
   tokio   peter  m
   madrid  susan  f
   london  alex   m

I want to create this list (where name and gender are lists):
   loc      name          gender
   -----------------------------
   tokio    [john, peter] [m]
   madrid   [susan]       [f]
   london   [alex]        [m]

How can I do this?


Thanks in advance.
Nico





More information about the Python-list mailing list