append to the end of a dictionary
Magnus Lycka
lycka at carmen.se
Wed Jan 25 07:42:32 EST 2006
Tim Chase wrote:
> I would lean towards using tuples, as in
>
> ports = [('5631','udp'), ('5632', 'tcp'), ('3389','tcp'), ('5900','tcp')]
>
> which you can then drop into your code:
>
> for (port, protocol) in ports:
> print port, protocol
> #do more stuff
>
> This allows you to use the same port with both UDP and TCP. If you want
> to ensure that only one pair (port+protocol) can be in the list, you can
> use a set() object:
But again, order will be lost (if that is of any consequence).
Another option would be to have a dict of sets keyed on port:
In Python 2.3:
>>> import sets
>>> ports = {}
>>> def add_port(port, prot):
... if port not in ports:
... ports[port]=sets.Set()
... ports[port].add(prot)
...
>>> add_port(25, 'tcp')
>>> add_port(25, 'udp')
>>> add_port(80, 'tcp')
>>> ports
{80: Set(['tcp']), 25: Set(['udp', 'tcp'])}
>>> add_port(80, 'tcp')
>>> ports
{80: Set(['tcp']), 25: Set(['udp', 'tcp'])}
Dicts have the obvious advantage that you can look up the protcols
used on a port without iterating over some sequence.
More information about the Python-list
mailing list