Python 如何根据字典值中的顺序将字典转换为列表
我有一本这样的字典:Python 如何根据字典值中的顺序将字典转换为列表,python,python-2.7,Python,Python 2.7,我有一本这样的字典: >>> d {'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1},'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'd': {'computer': 'mac', 'size': -1}} 我如何按大小对本词典的元素进行排序,但大小-1的项除外 因此,上述词典将转向: >>> converted {'a': {'foo
>>> d
{'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1},'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'd': {'computer': 'mac', 'size': -1}}
我如何按大小
对本词典的元素进行排序,但大小
-1的项除外
因此,上述词典将转向:
>>> converted
{'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1}, 'd': {'computer': 'mac', 'size': -1}}
更新
因为字典是不能订购的
是否可以将上述内容转换为带有字典的列表?i、 e
>>> converted_to_list
[{'foo': 'bar', 'something': 'else', 'size': 0}, {'icecream': 'orange', 'fruit': 'apple', 'size': 1}, {'computer': 'mac', 'size': -1}]
字典是无序的。这意味着您无法对其进行排序并使其保持有序
但是,如果希望按顺序迭代它(作为包含键和值的元组的列表),可以使用以下方法:
>>> d = {'c': {'icecream': 'orange', 'fruit': 'apple', 'size': 1},'a': {'foo': 'bar', 'something': 'else', 'size': 0}, 'd': {'computer': 'mac', 'size': -1}}
>>> sorted = sorted(d.items(), key=lambda x: x[1]['size'])
>>> sorted
[('d', {'computer': 'mac', 'size': -1}), ('a', {'something': 'else', 'foo': 'bar', 'size': 0}), ('c', {'fruit': 'apple', 'icecream': 'orange', 'size': 1})]
通过创建字典并添加以下所有值,可以轻松地将此列表转换回字典:
>>> g = {}
>>> for x in sorted:
... g[x[0]] = x[1]
...
>>> g
{'d': {'size': -1, 'computer': 'mac'}, 'a': {'something': 'else', 'size': 0, 'foo': 'bar'}, 'c': {'fruit': 'apple', 'icecream': 'orange', 'size': 1}}
Python字典是无序的
改用。您可以使用orderedICT
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”]
)。Gah,即按键,您实际上希望“按值”问题:答案是一样的:字典无法排序。查看OrderedDict
是否可以将其转换为基于大小元素的列表?普通字典不能按顺序排列。“你需要用a来代替。”Andy我更新了问题。我不认为这是一个长期的重复,如果你在另一个目录中有“size:-3
?如果t[1]['size']>=0
,或者你的订单将是错误的。