search

Home  >  Q&A  >  body text

I would like to ask why python2.7 and 3.6 use a for loop to output dictionary contents, so why are they sorted differently?

Excuse me, why are the dictionary contents sorted differently when using the same for in 2.7 and 3.6?

d = {'Adam':95,'Lisa':85,'Bart':59}
for k,v in d.items():
  print k,':',v
  #3.6的是print(k,':',k)

2.7 Output content

Lisa : 85
Adam : 95
Bart : 59

And 3.6 displays normally

Adam:95
Lisa:85
Bart:59
PHP中文网PHP中文网2753 days ago591

reply all(2)I'll reply

  • 某草草

    某草草2017-05-18 10:47:20

    Don’t worry too much about why the dictionary is sorted differently. Dictionaries are inherently unordered. If you want them to be ordered, you need to sort them before returning. In python3, such an operation is generally performed to reduce memory usage.

    reply
    0
  • 黄舟

    黄舟2017-05-18 10:47:20

    Because of this

    https://docs.python.org/3/wha...

    Cython 3.6 changes the implementation of dict to improve performance, and the automatic sorting of key names is a small side effect.

    reply
    0
  • Cancelreply