lists and dictionaries

anethema jefishman at
Thu Jul 12 04:49:02 CEST 2007

> li =  [ {'index': 0, 'transport': 'udp', 'service_domain':
> ''},
>         {'index': 1, 'transport': 'udp', 'service_domain':
> ''},
>         {'index': 0, 'transport': 'tcp', 'service_domain':
> ''},
>         {'index': 1, 'transport': 'tcp', 'service_domain':
> ''}]

I like this solution:

[{ 'transports'    : [d['transport'] for d in li if
d['service_domain'] == dom],
   'service_domain': dom,
 } for dom in set(d2['service_domain'] for d2 in li)]

merely because it takes one line.  Humorously enough, it appears to be
twice as efficient, at least when profiled on my computer, if speed is
important in this problem.  Not that this is the best way to do it

Anyway, since the generator expression isn't very clear:

def indexBasedToSDBased(li):
    newli = []
    # For each service domain in the set read from the original list
    for sdom in set(d['service_domain'] for d in li):
        # Append a new dictionary mapping all transports for this
            'service_domain': sdom,
            'transports': [d['transport'] for d in li if
d['service_domain'] == sdom]
    return newli

(which is slower than the one-line generator :-D  I love generator

  - Jeremy

More information about the Python-list mailing list