append to the end of a dictionary
Tim Chase
python.list at tim.thechases.com
Tue Jan 24 10:07:26 EST 2006
> that means I can neither have a dictionary with 2 identical keys but
> different values...?
correct :)
> I would need e.g. this:
> (a list of ports and protocols, to be treated later in a loop)
>
> ports = {'5631': 'udp', '5632': 'tcp', '3389': 'tcp', '5900': 'tcp'}
> #then:
> for port,protocol in ports.iteritems():
> ________print port,protocol
> ________#do more stuff
>
> What would be the appropriate pythonic way of doing this?
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:
set(ports)
(or in earlier versions:
from sets import Set
s = Set(ports)
which I happened to have here)
This will ensure that you don't end up with more than one item
with the same port+protocol pair.
-tkc
More information about the Python-list
mailing list