gpt4 book ai didi

python - 如何根据字典值中的顺序将字典转换为列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:43 25 4
gpt4 key购买 nike

我有一本这样的字典:

>>> d
{'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1},'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'd': {'computer': 'mac', 'size': -1}}

如何按size对这本字典的元素进行排序带有 size 的项目除外-1最终到来。

所以上面的字典将变成:

>>> converted
{'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1}, 'd': {'computer': 'mac', 'size': -1}}

更新

由于字典无法订购。

是否可以将上面的内容转换为带有字典的列表?即

>>> converted_to_list
[{'foo': 'bar', 'something': 'else', 'size': 0}, {'icecream': 'orange', 'fruit': 'apple', 'size': 1}, {'computer': 'mac', 'size': -1}]

最佳答案

您可以使用OrderedDict

from collections import OrderedDict

d = {'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1},'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'd': {'computer': 'mac', 'size': -1}}

print (OrderedDict(sorted(d.items(), key=lambda t: t[1]['size'] if t[1]['size']>=0 else float("inf") )))

由于您希望 -1 成为最后一个,因此只需将键设置为无限 (float["inf"]) 即可。

关于python - 如何根据字典值中的顺序将字典转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39236026/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com