Reputation: 31
I currently have some JSON that looks like this:
{
"Chile": {
"num_of_unique_ips": 1,
"num_of_unique_asns": 1,
"asns": {
"AS16629 CTC. CORP S.A. (TELEFONICA EMPRESAS)": 1
}
},
"China": {
"num_of_unique_ips": 1,
"num_of_unique_asns": 1,
"asns": {
"AS4808 China Unicom Beijing Province Network": 1
}
}, # this goes on and on for ever country
}
I converted it to a dictionary by running:
import json
login_by_country = json.loads(open('login_by_country.json', 'r'))
How would i go about sorting this dictionary by each country's num_of_unique_ips
value?
Upvotes: 1
Views: 122
Reputation: 142641
As @johrsharpe said in comment - dictionary doesn't have to keep order (but probably they will keep in in newest Python).
You can create list with pairs (num_of_unique_ips , country)
and then you can easily sort it and keep in order.
logins_by_country = {
"Chile": {
"num_of_unique_ips": 1,
"num_of_unique_asns": 1,
"asns": {
"AS16629 CTC. CORP S.A. (TELEFONICA EMPRESAS)": 1
}
},
"China": {
"num_of_unique_ips": 1,
"num_of_unique_asns": 1,
"asns": {
"AS4808 China Unicom Beijing Province Network": 1
}
}, # thi
}
data = [(val["num_of_unique_ips"], key) for key, val in logins_by_country.items()]
order = sorted(data)
print(order)
Result. It sorts by num_of_unique_ips
and country
(if they have the sam num_of_unique_ips
)
[(1, 'Chile'), (1, 'China')]
and now you can use it to get data from dictionary in expected order.
for number, country in order:
print(logins_by_country[country])
You can also use it to create OrderedDict
which will keep order
from collections import OrderedDict
new_dict = OrderedDict()
for number, country in order:
new_dict[country] = logins_by_country[country]
print(new_dict)
Upvotes: 0
Reputation: 42207
sorted(login_by_country.items(), key=lambda it: it[1]['num_of_unique_ips'])
This will return a list of (country, values_dict) pairs. You can convert it back to a dictionary while keeping the sorted order by passing it to OrderedDict
, or the regular dict
if you're using a version of Python which guarantees dict ordering (cpython 3.6+ or pypy 2.5).
Upvotes: 5