How to sort IP addresses stored in dictionary in Python?

sort ip address list python
python sort ipv6 addresses
python sorted
how to increment ip address in python
how to compare ip address in python
python3 sort ip addresses
python ip address validation
python change ip address

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:

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]))

How to sort a list of dictionaries by two values, one of which is an IP , How to sort IP addresses stored in dictionary in Python? I have a piece of code that looks like this: ipCount = defaultdict(� python; sort; Python provides a a sort and sorted function. Sort changes the original list, while sorted creates a copy of the list, without changing the original list. So the sort version is faster, but it works only on lists, while sorted works on any iterable. Now the problem is that if I try to sort IPs like strings, they won’t be sorted properly.

Use the key parameter of sorted to convert your ip to an integer, for example:

list_of_ips = ['192.168.204.111', '192.168.99.11', '192.168.102.105']
sorted(list_of_ips, key=lambda ip: long(''.join(["%02X" % long(i) for i in ip.split('.')]), 16))

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:

from socket import inet_aton
import struct
list_of_ips = ['192.168.204.111', '192.168.99.11', '192.168.102.105']
sorted(list_of_ips, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0])

How to sort IP addresses stored in dictionary in Python , So the sort version is faster, but it works only on lists, while sorted works on any iterable. Now the problem is that if I try to sort IPs like strings, they won't be sorted � Python provides a a sort and sorted function. Sort changes the original list, while sorted creates a copy of the list, without changing the original list. So the sort version is faster, but it works only on lists, while sorted works on any iterable. Now the problem is that if I try to sort IPs like strings, they won’t be sorted properly.

A clean way of handling the right order is using Pythons ipaddress module. You can transform the Strings into IPv4Address representations and sort them afterwards. Here's a working example with list objects (Tested with Python3):

import ipaddress

unsorted_list = [
  '192.168.102.105',
  '192.168.204.111',
  '192.168.99.11'
]

new_list = []

for element in unsorted_list:
  new_list.append(ipaddress.ip_address(element))

new_list.sort()

# [IPv4Address('192.168.99.11'), IPv4Address('192.168.102.105'), IPv4Address('192.168.204.111')]
print(new_list)

How to Sort IP Addresses With Python-, You can use pandas argsort method. Like this: df.iloc[np.argsort(list(map(socket. inet_aton,list_of_ips)))]� In this blog, we have discussed how to sort a dictionary in python. Dictionary can be a optimized way of dealing with data which involves key value pairs. It becomes easier to work on dictionaries since they are mutable in nature and have a search time complexity less than that of a list.

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.

from socket import inet_aton,inet_ntoa
import struct

def ip2long(ip):
    packed = inet_aton(ip)
    lng = struct.unpack("!L", packed)[0]
    return lng

convert the number back into an ip using this function:

def long2ip(lng):
    packed = struct.pack("!L", lng)
    ip=inet_ntoa(packed)
    return ip


>>> ip2long('192.168.1.1')
3232235777
>>> ip2long('1.2.3.4')
16909060
>>> long2ip(3232235777)
'192.168.1.1'
>>> long2ip(16909060)
'1.2.3.4'

Is there a way to sort ip-addresses in a dictionary?, I have a piece of code that looks like this: ipCount = defaultdict(int) for logLine in logLines: date, serverIp, clientIp = logLine.split("� Sort dictionary contents by Value. To sort dictionary elements by value we will use the same sorted() function and pass a key function that will return the 1th index element of tuple i.e. the value field from the key/value pair,

What are my options here?

The two obvious one that come to my mind are:

  1. Preformatting the strings with the IP when you store them as from the link you put in your question.
  2. Pass a sorting function to 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:

>>> ip = '192.168.1.1'
>>> print('%3s.%3s.%3s.%3s' % tuple(ip.split('.')))
192.168.  1.  1
>>> print('%s.%s.%s.%s' % tuple([s.zfill(3) for s in ip.split('.')]))
192.168.001.001

Example of sorting function

Well... Ferdinand Beyer in his answer seems to have already offered an excellent solution for this approach! :)

How to sort IP addresses stored in dictionary in Python?, Return an IPv4Address or IPv6Address object depending on the IP address passed as Address objects are hashable, so they can be used as keys in dictionaries. There are some times however, where you may wish to have ipaddress sort� How to sort by key in Python 3.7. The big change in Python 3.7 is that the dictionaries are now ordered by default. You can generate sorted dict using dict comprehensions. Using OrderedDict might still be preferable for the compatibility sake. Do not use sorted(d.items()) without key. See:

ipaddress — IPv4/IPv6 manipulation library — Python 3.8.4rc1 , Sorting IP addresses in Python This is fairly easily achieved if you stored like list of IPs as ipaddress objects: >>> import ipaddress� This will sort the dictionary by the values of each entry within the dictionary from smallest to largest. To sort it in descending order just add reverse=True: sorted(d.items(), key=lambda x: x[1], reverse=True) Input: d = {'one':1,'three':3,'five':5,'two':2,'four':4} a = sorted(d.items(), key=lambda x: x[1]) print(a) Output:

Sorting IP addresses in Python, The last built-in method that we'll take a look at for lists is sort(). In the next example, we have a list of IP addresses in non-sequential order, and sort() is used to update the a list that stored different types of contextual objects (or even data types). As luck would have it, this is exactly where Python dictionaries come into� Python Dictionary [ 40 exercises with solution] [An editor is available at the bottom of the page to write and execute the scripts.] 1. Write a Python script to sort (ascending and descending) a dictionary by value. Go to the editor. Click me to see the sample solution. 2. Write a Python script to add a key to a dictionary. Go to the editor

Network Programmability and Automation: Skills for the , Challenge - Scrape a Book Store! change a decimal to time in datetime python � change colorbar size and place python � change column name df � change column� Load the Dictionary and perform the following operations: First, sort the keys alphabetically using key_value.iterkeys () function. Second, sort the keys alphabetically using sorted (key_value) function & print the value corresponding to it.

Comments
  • You can also do this with the map function: sorted(ipCount.items(), key=lambda x:tuple(map(int, x.split('.')))))
  • I see the updated answers using inet_aton are different: Ludo's call struct.unpack and Ferdinand's does not. Is this function call necessary for ordering or not?
  • @randomtoor: It is not necessary. inet_aton returns a string of 4 characters, and Python knows how to compare and sort strings.
  • The Updated version is awesome! Should be the primary version & answer IMO.
  • I'd like to give this a +1 but it needs a little explanation. Specifically, why the [0]?
  • +1 for recommending the socket module. But since the question is about sorting, you might want to give an example on how to use it in this context.