sorting - How to sort IP addresses stored in dictionary in Python? -
i have piece of code looks this:
ipcount = defaultdict(int) logline in loglines: date, serverip, clientip = logline.split(" ") ipcount[clientip] += 1 clientip, hitcount in sorted(ipcount.items), key=operator.itemgetter(0)): print(clientip)
and kind of sorts ip's, this:
192.168.102.105 192.168.204.111 192.168.99.11
which not enough since not recognize 99 smaller number 102 or 204. output this:
192.168.99.11 192.168.102.105 192.168.204.111
i found this, not sure how implement in code, or if possible since use dictionary. options here? thank you..
you can use custom key
function return sortable representation of strings:
def split_ip(ip): """split ip address given string 4-tuple of integers.""" return tuple(int(part) part in ip.split('.')) def my_key(item): return split_ip(item[0]) items = sorted(ipcount.items(), key=my_key)
the split_ip()
function takes ip address string '192.168.102.105'
, turns tuple of integers (192, 168, 102, 105)
. python has built-in support sort tuples lexicographically.
update: can done easier using inet_aton()
function in socket
module:
import socket items = sorted(ipcount.items(), key=lambda item: socket.inet_aton(item[0]))
Comments
Post a Comment