按字典值的值对字典进行排序

iam*_*l4v 1 python sorting dictionary

我目前有一些如下所示的 JSON:

{
    "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
}
Run Code Online (Sandbox Code Playgroud)

我通过运行将其转换为字典:

import json
login_by_country = json.loads(open('login_by_country.json', 'r'))
Run Code Online (Sandbox Code Playgroud)

我将如何按照每个国家/地区的值对这本词典进行排序num_of_unique_ips

Mas*_*inn 5

sorted(login_by_country.items(), key=lambda it: it[1]['num_of_unique_ips'])
Run Code Online (Sandbox Code Playgroud)

这将返回(国家,values_dict)对的列表。您可以将其转换回字典,同时通过将其传递给 来保持排序顺序,或者如果您使用的是保证字典排序的 Python 版本(cpython 3.6+ 或 pypy 2.5),则将其传递给OrderedDict常规版本。dict