首页 > 解决方案 > 嵌套 Python 字典排序

问题描述

我有一个具有以下格式的 python 字典。

{'range_qty': 
  {'0 to 10 qty': 5,
  'more than 5000 qty': 18,
  '500 to 1000 qty': 20,
  '200 to 500 qty': 19,
  '1000 to 5000 qty': 15,
  '10 to 50 qty': 3,
  '50 to 200 qty': 14}}

如何按键对这本字典进行排序?我需要像这样的输出

{'range_qty': 
  {'0 to 10 qty': 5,
  '10 to 50 qty': 3,
  '50 to 200 qty': 14,
  '200 to 500 qty': 19,
  '500 to 1000 qty': 20,
  '1000 to 5000 qty': 15,
  'more than 5000 qty': 18,
  }}

标签: pythonpython-3.xsortingdictionary

解决方案


使用自定义排序。

前任:

import sys


def cust_sort(val):
    i = val[0].split(" ", 1)[0]
    if not i.isdigit():
        return sys.maxsize
    return int(i)

data = {'range_qty': 
  {'0 to 10 qty': 5,
  'more than 5000 qty': 18,
  '500 to 1000 qty': 20,
  '200 to 500 qty': 19,
  '1000 to 5000 qty': 15,
  '10 to 50 qty': 3,
  '50 to 200 qty': 14}}

data = sorted(data['range_qty'].items(), key=cust_sort)
#or data = {'range_qty': dict(sorted(data['range_qty'].items(), key=cust_sort))}
print(data)

输出:

[('0 to 10 qty', 5),
 ('10 to 50 qty', 3),
 ('50 to 200 qty', 14),
 ('200 to 500 qty', 19),
 ('500 to 1000 qty', 20),
 ('1000 to 5000 qty', 15),
 ('more than 5000 qty', 18)]

推荐阅读