0

I've listed all over SO but didn't find the correct answer for my situation. I found this code to sort a dictionary:

min_key = sorted(d.items(), key=lambda x:x[1])[0]

And it does the sorting right, but now I need to run this code for

{ '10.8.68.192': 9, '10.8.69.42': 9}

and for

{ '10.8.69.42': 9, '10.8.68.192': 9 }

and I need it return '10.8.68.192' no matter in what order are they(if values are same sort by key). Any ideas ?

1
  • y u want to sort, if you want specific ip??? Commented Nov 28, 2014 at 10:36

3 Answers 3

4

First of all use min() here not sorted()* if you want the smallest key that satisfies your condition, and you can use a tuple to specify multiple arguments for comparison.

>>> d = { '10.8.68.192': 9, '10.8.69.42': 9}
>>> min(d, key=lambda x: (d[x], map(int, x.split('.'))))
'10.8.68.192'
#or
>>> import socket
>>> min(d, key=lambda x: (d[x], socket.inet_aton(x)))
'10.8.68.192'

* (min() takes O(N) time and O(1) memory, on the other hand sorted() will take O(NlogN) time and will create an unnecessary list in memory).

Sign up to request clarification or add additional context in comments.

Comments

3

You can sort on a tuple, like sorted(d.items(), key=lambda x: (x[1], x[0])).

Note that using an IP address string for sorting will order lexicographically, which places e.g. 12.0.0.10 before 127.0.0.2. socket.inet_aton(ip) will convert an IPv4 address to a 32-bit integer which fixes this problem.

3 Comments

This will not work as you're comparing numbers in string lexicographically.
(if values are same sort by key).
While you are correct about lexicographic ordering, I would argue that the proper way to compare IPv4 addresses is not to split them into a tuple on the decimal places, but to convert entirely to/from an integer.
-1

for this i will use regex:

>>> import re
>>> my_dict = { '10.8.69.42': 9, '10.8.68.192': 9 }
>>> re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.192'," ".join(my_dict.keys()))
['10.8.68.192']

1 Comment

What makes you think that he always wants the IP that ends in 192? He wants the lowest IP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.