Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何排序字典python(排序)_Python_Sorting_Dictionary - Fatal编程技术网

如何排序字典python(排序)

如何排序字典python(排序),python,sorting,dictionary,Python,Sorting,Dictionary,我使用Python字典: >>> a = {} >>> a["w"] = {} >>> a["a"] = {} >>> a["s"] = {} >>> a {'a': {}, 's': {}, 'w': {}} 我需要: >>> a {'w': {}, 'a': {}, 's': {}} 我怎样才能得到我填字典的顺序? OrderedDict是一种能够记住钥匙先放的顺序的口述 插入。如

我使用Python字典:

>>> a = {}
>>> a["w"] = {}
>>> a["a"] = {}
>>> a["s"] = {}
>>> a
{'a': {}, 's': {}, 'w': {}}
我需要:

>>> a
{'w': {}, 'a': {}, 's': {}}
我怎样才能得到我填字典的顺序?

OrderedDict是一种能够记住钥匙先放的顺序的口述 插入。如果新条目覆盖现有条目,则原始条目 插入位置保持不变。删除条目并 重新插入会将其移动到末端


您应该使用
orderedict
而不是
Dict

对于python 3.6及更高版本,您可以使用OrderedDict,dict维护插入顺序
>>> import collections
>>> a = collections.OrderedDict()
>>> a['w'] = {}
>>> a['a'] = {}
>>> a['s'] = {}
>>> a
OrderedDict([('w', {}), ('a', {}), ('s', {})])
>>> dict(a)
{'a': {}, 's': {}, 'w': {}}