【问题标题】:Nested Python Dictionary Sorting嵌套 Python 字典排序
【发布时间】:2020-05-06 08:53:42
【问题描述】:

我有一个 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,
  }}

【问题讨论】:

  • 你有没有尝试过解决这个问题?
  • 我很好奇 - 你为什么要对字典进行排序?
  • This 实际上是您在互联网上搜索“python sort dict”时找到的第一个链接
  • 请注意,所有这些“值”都是字符串,不会根据值或大小进行排序。如果要按数量排序,将这些转换成实际值如01050等,并测量从最后一个键到当前键的差距以确定两者之间的数量。
  • @mapf 我倾向于同意您的链接,问题是 OP 的值与关键文本不对应。例如,50 to 200 qty 的值是 14,它没有介于两者之间。 OP 还希望通过键而不是值对其进行排序,尽管链接答案的变化很小。

标签: python python-3.x sorting dictionary


【解决方案1】:

使用自定义排序。

例如:

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)]

【讨论】:

  • 谢谢兄弟。非常感谢您的努力。
【解决方案2】:

根据您的 python 版本,默认情况下您的 dict 可能不存储订单。但是,如果您想按照列出的顺序迭代此 dict,则可以在使键统一的情况下使用 sort。 IE 使它们都以 int 开头。所以你可以把more than 5000 qty改成5000 or more qty

data = {'range_qty':
  {'0 to 10 qty': 5,
  '5000 or more 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}}

for qty in sorted(data['range_qty'], key=lambda text: int(text.split()[0])):
    print(f"{qty}: {data['range_qty'][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
5000 or more qty: 18

【讨论】:

  • 感谢兄弟的努力。
猜你喜欢
  • 2021-07-27
  • 2020-09-17
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 1970-01-01
相关资源
最近更新 更多