Can internal dictionary order change?

前端 未结 3 749
一生所求
一生所求 2021-01-19 04:08
exampleDict = {\'a\':1, \'b\':2, \'c\':3, \'d\':4}

The above dictionary initially iterated through in this order:

b=2
d=4
a=1
c=3
<         


        
相关标签:
3条回答
  • 2021-01-19 04:27

    Dict don't have a fixed order, from documentation

    CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

    If you really need to keep it ordered, there is an object called OrderedDict :

    from collections import OrderedDict
    exampleDict = OrderedDict({'a':1, 'b':2, 'c':3, 'd':4})
    

    see also OrderedDict documentation here

    0 讨论(0)
  • 2021-01-19 04:27

    Yes. If you do change the code between different calls to the dict, the order of iteration will change.

    From the docs

    If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

    If the order of insertion matter, check out the OrderedDict class

    0 讨论(0)
  • 2021-01-19 04:44

    Curious about why you want them ordered. Any chance it's just for consistent logging/printing or similar? If so, you can sort the keys alphabetically. See other article: How to sort dictionary by key in numerical order Python

    0 讨论(0)
提交回复
热议问题