如何按子值对嵌套python字典项进行排序,并按降序描述dictionary_____保存该字典项。
分类前
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希望按字典项的子值(即:“数量”)对字典项进行排序,输出应该如下所示:-
分类后
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}
}发布于 2020-10-19 04:12:58
我建议提取排序的密钥,然后创建一个新的字典。
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发布于 2020-10-19 04:23:47
你可以试试这个:
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)https://stackoverflow.com/questions/64420938
复制相似问题