how to order dictionary python (sorting)

前端 未结 2 1705
粉色の甜心
粉色の甜心 2020-12-19 18:46

I use Python dictionary:

>>> a = {}
>>> a[\"w\"] = {}
>>> a[\"a\"] = {}
>>> a[\"s\"] = {}
>>> a
{\'a\': {}, \'s\         


        
相关标签:
2条回答
  • 2020-12-19 19:22

    you should use OrderedDict instead of Dict.

    http://docs.python.org/2/library/collections.html

    0 讨论(0)
  • 2020-12-19 19:40

    http://docs.python.org/2/library/collections.html#collections.OrderedDict

    An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

    >>> import collections
    >>> a = collections.OrderedDict()
    >>> a['w'] = {}
    >>> a['a'] = {}
    >>> a['s'] = {}
    >>> a
    OrderedDict([('w', {}), ('a', {}), ('s', {})])
    >>> dict(a)
    {'a': {}, 's': {}, 'w': {}}
    
    0 讨论(0)
提交回复
热议问题