简体   繁体   中英

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_____

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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