lists and dictionaries
anethema
jefishman at gmail.com
Wed Jul 11 22:49:02 EDT 2007
> li = [ {'index': 0, 'transport': 'udp', 'service_domain':
> 'dp0.example.com'},
> {'index': 1, 'transport': 'udp', 'service_domain':
> 'dp1.example.com'},
> {'index': 0, 'transport': 'tcp', 'service_domain':
> 'dp0.example.com'},
> {'index': 1, 'transport': 'tcp', 'service_domain':
> 'dp1.example.com'}]
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
either.
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
domain
newli.append({
'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
expressions)
- Jeremy
More information about the Python-list
mailing list