通过Python中的字典中的字典键进行排序 [英] Sort by key of dictionary inside a dictionary in Python

查看:332
本文介绍了通过Python中的字典中的字典键进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用remaining_pcs或discount_ratio的值排序以下字典?

How to sort the following dictionary by the value of "remaining_pcs" or "discount_ratio"?

promotion_items = {
    'one': {'remaining_pcs': 100, 'discount_ratio': 10},
    'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}

编辑

我的意思是得到上面的字典的排序列表,不排序字典本身。

What I mean is getting a sorted list of above dictionary, not to sort the dictionary itself.

推荐答案

你只能排序(或项目或值)到一个单独的列表(正如我在几年前在安德鲁引用的食谱中写的)。例如,按照您所规定的标准对钥匙进行排序:

You can only sort the keys (or items or values) of a dictionary, into a separate list (as I wrote years ago in the recipe that @Andrew's quoting). E.g., to sort keys according to your stated criteria:

promotion_items = {
    'one': {'remaining_pcs': 100, 'discount_ratio': 10},
    'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}
def bypcs(k):
  return promotion_items[k]['remaining_pcs']
byrempcs = sorted(promotion_items, key=bypcs)
def bydra(k):
  return promotion_items[k]['discount_ratio']
bydiscra = sorted(promotion_items, key=bydra)

这篇关于通过Python中的字典中的字典键进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆