简体   繁体   English

对嵌套的python字典进行排序

[英]Sort nested python dictionary

How to sort nested python dictionary items by their sub-values and save that dictionary items in descending order Describing dictionary_____如何按子值对嵌套的 Python 字典项进行排序并按降序保存该字典项描述字典_____

Before sorted排序前

    dict={
          "Bob": {"Buy": 25, "Sell": 33, "Quantity": 100}
          "Moli": {"Buy": 75, "Sell": 53, "Quantity": 300}
          "Annie": {"Buy": 74, "Sell": 83, "Quantity": 96}
          "Anna": "Buy": 55, "Sell": 83, "Quantity": 154}
         }

I want to sort dictionary items in descending order by their sub- values(ie: "Quantity") and the output should be like this:----我想按其子值(即:“数量”)按降序对字典项进行排序,输出应如下所示:----

After sorted排序后

    dict={
          "Moli": {"Buy": 75, "Sell": 53, "Quantity": 300}
          "Anna": "Buy": 55, "Sell": 83, "Quantity": 154}
          "Bob": {"Buy": 25, "Sell": 33, "Quantity": 100}
          "Annie": {"Buy": 74, "Sell": 83, "Quantity": 96}
         }

I recommend extracting the sorted keys and then creating a new dictionary.我建议提取排序后的键,然后创建一个新字典。

def sort_by_quantity(dic):
  keys = sorted(dic.items(), key=lambda x: x[1]['Quantity']) # list of sorted keys
  return dict((x, y) for x, y in keys) # convert tuple back to dict

You can try this:你可以试试这个:

dictt={"Bob": {"Buy": 25, "Sell": 33, 
"Quantity": 100},"Moli": {"Buy": 75, "Sell": 53, 
"Quantity": 300},"Annie": {"Buy": 74, "Sell": 83, "Quantity": 96}, 
"Anna": {"Buy": 55, "Sell": 83, "Quantity": 154}
}
sdct = dictt.copy()
def func(d):
    `return sdct[d]['Quantity']
dct = sorted(dictt, key=func, reverse=True)
newDict = {i: dictt[i] for i in dct}
print(newDict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM