lists and dictionaries

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Wed Jul 11 22:09:42 CEST 2007


On Jul 11, 12:08 pm, Ladislav Andel <lad... at iptel.org> wrote:
> Hi,
> I have a list of dictionaries.
> e.g.
> [{'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'}]
>
> how could I make a new list of dictionaries which would look like:
> [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'},
> {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}]


You provide scant information for this task.  For example, is the
new list ordered or unordered?  Can the list corresponding to the
'transports' key contain duplicates?

Regardless, here's an example:

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'}]


group_by_service_domain = dict()
for d in li:
    sd = d['service_domain']
    nested_d = group_by_service_domain.setdefault(sd,
        {'service_domain': sd, 'transports': set()})
    nested_d['transports'].add(d['transport'])

new_li = [dict(transports=list(d['transports']),
    service_domain=d['service_domain']) for d in
    group_by_service_domain.values()]

print new_li

--
Hope this helps,
Steven





More information about the Python-list mailing list