How to iterate through two dicts efficiently

Chris Rebert clp2 at rebertia.com
Tue Jul 19 19:25:25 CEST 2011


On Tue, Jul 19, 2011 at 7:20 AM, J <jnr.gonzalez at googlemail.com> wrote:
> Hi guys,
>
> Thank you for your suggestions.  I have managed to get my whole script to execute in under 10 seconds by changing the 'for loop' I posted above to the following:-
>
> for opco in Cn:
>        for service in Cn[opco]:
>                ack = set(Cn[opco][service]['RECV']) & set(Pr['13'])
>                for jarid in ack:
>                        Cn[opco][service].setdefault('ACK', set()).add(jarid)
>                nack = set(Cn[opco][service]['RECV']) & set(Pr['14'])
>                for jarid in nack:
>                        Cn[opco][service].setdefault('NACK', set()).add(jarid)
>                retry = set(Cn[opco][service]['RECV']) & set(Pr['504'])
>                for jarid in retry:
>                        Cn[opco][service].setdefault('RETRY', set()).add(jarid)
>                retry1 = set(Cn[opco][service]['RECV']) & set(Pr['505'])
>                for jarid in retry1:
>                        Cn[opco][service].setdefault('RETRY', set()).add(jarid)

Code duplication ahoy! Let's refactor that:

pairs = [('ACK', '13'), ('NACK', '14'), ('RETRY', '504'), ('RETRY', '505')]
for opco in Cn:
    for service in Cn[opco]:
        for msg, prkey in pairs:
            ids = set(Cn[opco][service]['RECV']) & set(Pr[prkey])
            for jarid in ids:
                Cn[opco][service].setdefault(msg, set()).add(jarid)

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list