How to numerically sort IP address

Viewed 46

I have a list of dict having ip address. i want to sort them numerically

a = [{'from': '10.246.47.121' },{'from': '10.60.0.111'}, {'from': '192.168.156.113'}, {'from': '192.168.20.100'}]

below is my code

b = sorted(a, key=operator.itemgetter('from'))

this is giving the following output

[{'from': '10.246.47.121'}, {'from': '10.60.0.111'}, {'from': '192.168.156.113'}, {'from': '192.168.20.100'}]

i want to get output like this

a = [{'from': '10.60.0.111'}, {'from': '10.246.47.121' }, {'from': '192.168.20.100'}, {'from': '192.168.156.113'}]

any help is much appreciated

1 Answers

Like this

a.sort(key=lambda x: [int(y) for y in x['from'].split('.')])
Related