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

问题描述 投票:0回答:2

我目前有一些看起来像这样的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
}

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

import json
login_by_country = json.loads(open('login_by_country.json', 'r'))

我如何根据每个国家的num_of_unique_ips值对这本字典进行排序?

python sorting dictionary
2个回答
4
投票
sorted(login_by_country.items(), key=lambda it: it[1]['num_of_unique_ips'])

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


0
投票

正如@johrsharpe在评论中所说 - 字典不必保持秩序(但可能它们将保留在最新的Python中)。

您可以使用(num_of_unique_ips , country)对创建列表,然后您可以轻松地对其进行排序并保持有序。

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)

结果。它由num_of_unique_ipscountry排序(如果他们有sam num_of_unique_ips

[(1, 'Chile'), (1, 'China')]

现在您可以使用它以预期的顺序从字典中获取数据。

for number, country in order:
    print(logins_by_country[country])

您也可以使用它来创建OrderedDict,它将保持秩序

from collections import OrderedDict

new_dict = OrderedDict()

for number, country in order:
    new_dict[country] = logins_by_country[country]

print(new_dict)
© www.soinside.com 2019 - 2024. All rights reserved.