How to sort IP addresses stored in dictionary in Python?

You can use a custom key function to return a sortable representation of your strings:

def split_ip(ip):
    """Split a IP address given as string into a 4-tuple of integers."""
    return tuple(int(part) for 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 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 the socket module:

import socket
items = sorted(ipCount.items(), key=lambda item: socket.inet_aton(item[0]))

Leave a Comment