Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort IP addresses stored in dictionary in Python?

Tags:

People also ask

How do you sort a dictionary item in Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse. Dictionaries are unordered data structures.

Can you use sort on a dictionary Python?

Introduction. We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.

How do I sort my IP address?

Approach: The idea is to use a custom comparator to sort the given IP addresses. Since IPv4 has 4 octets, we will compare the addresses octet by octet. Check the first octet of the IP Address, If the first address has a greater first octet, then return True to swap the IP address, otherwise, return False.


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..