Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dictionary values to int in Python?

I have a program that returns a set of domains with ranks like so:

ranks = [
    {'url': 'example.com', 'rank': '11,279'},
    {'url': 'facebook.com', 'rank': '2'},
    {'url': 'google.com', 'rank': '1'}
]

I'm trying to sort them by ascending rank with sorted:

results = sorted(ranks,key=itemgetter("rank"))

However, since the values of "rank" are strings, then it sorts them alphanumerically instead of by ascending value:

1. google.com: 1

2. example.com: 11,279

3. facebook.com: 2

I need to convert the values of only the "rank" key to integers so that they'll sort correctly. Any ideas?

like image 970
BaButtons Avatar asked Aug 10 '15 15:08

BaButtons


1 Answers

You are almost there. You need to convert the picked values to integers after replacing ,, like this

results = sorted(ranks, key=lambda x: int(x["rank"].replace(",", "")))

For example,

>>> ranks = [
...     {'url': 'example.com', 'rank': '11,279'},
...     {'url': 'facebook.com', 'rank': '2'},
...     {'url': 'google.com', 'rank': '1'}
... ]
>>> from pprint import pprint
>>> pprint(sorted(ranks, key=lambda x: int(x["rank"].replace(",", ""))))
[{'rank': '1', 'url': 'google.com'},
 {'rank': '2', 'url': 'facebook.com'},
 {'rank': '11,279', 'url': 'example.com'}]

Note: I just used pprint function to pretty print the result.

Here, x will be the current object for which the key value being determined. We get the value of rank attribute from it, replace , with empty string and then converted that to a number with int.


If you don't want to replace , and handle it properly, then you can use locale module's atoi function, like this

>>> import locale
>>> pprint(sorted(ranks, key=lambda x: int(locale.atoi(x["rank"]))))
[{'rank': '1', 'url': 'google.com'},
 {'rank': '2', 'url': 'facebook.com'},
 {'rank': '11,279', 'url': 'example.com'}]
like image 147
thefourtheye Avatar answered Oct 05 '22 11:10

thefourtheye