I have a 2D dictionary in python indexed by two IPs. I want to group the dictionary by the first key.
For example, the before would look like this:
myDict["182.12.17.50"]["175.12.13.14"] = 14
myDict["182.15.12.30"]["175.12.13.15"] = 10
myDict["182.12.17.50"]["185.23.15.69"] = 30
myDict["182.15.12.30"]["145.33.34.56"] = 230
so
for key1, key2 in myDict:
print key1 +" " +key2 +" " +myDict[key1, key2]
would print
182.12.17.50 175.12.13.14 14
182.15.12.30 175.12.13.15 10
182.12.17.50 185.23.15.69 30
182.15.12.30 145.33.34.56 230
But I want to sort it so it would print
182.12.17.50 175.12.13.14 14
182.12.17.50 185.23.15.69 30
182.15.12.30 175.12.13.15 10
182.15.12.30 145.33.34.56 230
Any idea how this could be accomplished?
Well, there are a variety of options. One of them would be to sort the keys before printing, something like this:
Another option would be to use the sorteddict class from the blist module (disclaimer: I’m the author 🙂 ), which will always return the keys in sorted order.
In either cases, since the keys are IP addresses, you might want to write a custom “key” function to pass to sort/sorted/sorteddict so they will sorted by their numeric value rather than lexicographically as a string.