lists and dictionaries

Ladislav Andel ladaan at iptel.org
Tue Jul 17 04:59:36 EDT 2007


Hi,
could you actually help me further?
I thought it will quite easy but I've been programming in python just 
for a month.
I need to add extra items in new list.
So here is example:

I have a list of dictionaries.
e.g.
[{'index': 0, 'ip_addr': '1.2.3.4', 'server-name':'Asterisk', 'transport': 'udp', 'service_domain': 'dp0.example.com'},
{'index': 1, 'ip_addr': '5.6.7.8', 'server-name':'Asterisk', 'transport': 'udp', 'service_domain': 'dp1.example.com'},
{'index': 0, 'ip_addr': '1.2.3.4', 'server-name': 'Yes', 'transport': 'tcp', 'service_domain': 'dp0.example.com'},
{'index': 1, 'ip_addr': '5.6.7.8', 'server-name': 'Yes', 'transport': 'tcp', 'service_domain': 'dp1.example.com'}]

The server-name within tcp test is not known because I just open connection at port where the server should run and if succeeded then server-name = Yes. In newlist should be the server name Asterisk though.

how could I make a new list of dictionaries which would look like:
[{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com', 'ip_addr': '1.2.3.4', 'server-name':'Asterisk'},
{'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com', 'ip_addr': '5.6.7.8', 'server-name':'Asterisk'}]

I was trying to implement it to existing code but I'm not really 
successful so far.

Thank you for your help.

Lada

Bart Ogryczak wrote:
> On 11 jul, 21:08, 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'}]
>>
>> Could you help me, please?
>>     
>
> doms = {}
> for entry in oldList:
>     doms.setdefault(entry['service_domain'],
> []).append(entry['transport'])
> newList = [{'transports': t, 'service_domain': d} for d,t in
> doms.iteritems()]
>
>
>   




More information about the Python-list mailing list