append to the end of a dictionary

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Jan 24 22:07:49 CET 2006


On Tue, 24 Jan 2006 16:01:48 +0100, Yves Glodt wrote:

> that means I can neither have a dictionary with 2 identical keys but 
> different values...?

Yes, that's 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'}

Which will work perfectly fine as a dict, because you have unique keys but
multiple values. Two keys with the same value is allowed.

Question: is there a reason the port numbers are stored as strings instead
of numbers?


> #then:
> for port,protocol in ports.iteritems():
> ________print port,protocol
> ________#do more stuff
> 
> 
> What would be the appropriate pythonic way of doing this?


Is it even possible to have multiple protocols listening on the
same port? Doesn't matter I suppose. Associating multiple values to the
same key is easy: just store the values in a list:


foods = { "red": ["apple", "tomato", "cherry"], 
          "green": ["apple", "lettuce", "lime"], 
          "blue": ["blueberry"],
          "yellow": ["butter", "banana", "apple", "lemon"] }

# add a new colour
foods["orange"] = ["orange"]
# add a new food to a colour
foods["red"].append("strawberry")

for colour, foodlist in foods.iteritems():
    for food in foodlist:
        print colour, food


If you need to use the keys in a particular order, extract the keys and
sort them first:

colours = foods.keys()
colours.sort()
for colour in colours:
    for food in foods[colour]:
        print colour, food



-- 
Steven.




More information about the Python-list mailing list