I have a piece of code that looks like this:
ipCount = defaultdict(int)
for logLine in logLines:
date, serverIp, clientIp = logLine.split(" ")
ipCount[clientIp] += 1
for clientIp, hitCount in sorted(ipCount.items), key=operator.itemgetter(0)):
print(clientIp)
and it kind of sorts IP's, but like this:
192.168.102.105
192.168.204.111
192.168.99.11
which is not good enough since it does not recognize that 99 is a smaller number than 102 or 204. I would like the output to be like this:
192.168.99.11
192.168.102.105
192.168.204.111
I found this, but I am not sure how to implement it in my code, or if it is even possible since I use dictionary. What are my options here? Thank you..
You can use a custom
key
function to return a sortable representation of your strings:The
split_ip()
function takes an IP address string like'192.168.102.105'
and turns it into a tuple of integers(192, 168, 102, 105)
. Python has built-in support to sort tuples lexicographically.UPDATE: This can actually be done even easier using the
inet_aton()
function in thesocket
module:Use the key parameter of sorted to convert your ip to an integer, for example:
EDIT:
Gryphius proposes a solution with the socket module, and so why not use it to make the conversion from ip to long as it is cleaner:
if your application does lots of things like "find ips in range x", "sort by ip" etc its often more convenient to store the numeric value of the ip internally and work with this one.
convert the number back into an ip using this function:
I think this will help you: PEP265 (sorting dictionieries by value). Just extend the sorted function.
The two obvious one that come to my mind are:
sorted()
function when you perform the ordering.Which is best depends from the amount of data you have to process (you will notice an increased performance for method #1 only for very large amount of data) and from what you will need to do with said sorted list of IP (if you preformat the strings, you might then need to change them again before feeding them as arguments to other functions, for example).
Example of preformatting
Maintain the IP as a string, but uses spaces or zeroes to solve the variable number of digits problem:
Example of sorting function
Well... Ferdinand Beyer in his answer seems to have already offered an excellent solution for this approach! :)