Aditya Aditya - 2 months ago 13
Python Question

Sort dict keys into list

I have a dictionary containing IP addresses and hd space for each IP.

{'192.168.100.102': '7.3G', '192.168.100.103': '3.5G', '192.168.100.101': '7.4G', '192.168.100.107': '17G'}

I want to take three IPs with the greatest space and put them into a list. Is this possible?

Answer

Slice off the trailing 'G' part from the values and convert them to float in the sort key:

ips = {'192.168.100.102': '7.3G', '192.168.100.103': '3.5G', '192.168.100.101': '7.4G', '192.168.100.107': '17G'}

sorted_ips = sorted(ips, key=lambda x: float(ips[x][:-1]), reverse=True)[:3]
print(sorted_ips)
# ['192.168.100.107', '192.168.100.101', '192.168.100.102']