python - 用sorted对字典排序,打印的结果为什么会是这样?
巴扎黑
巴扎黑 2017-04-18 09:41:00
0
4
327

巴扎黑
巴扎黑

reply all(4)
Ty80
# 你新建了一个dict
In[1]: dic = {'k1': 1, 'k2': 3, 'k3': 2}
# 然后用sorted对字典的key按照字母升序排列
In[2]: sorted(dic.items())
# 注意看输出, 上面的排序是重新生成了一个由(key, value)组成的list, 并没有作用到dict上, 另外dict的key是hashtable, 本身无序, 是不能对其排序的
Out[2]: [('k1', 1), ('k2', 3), ('k3', 2)]
In[3]: dic
# dict在这里并没有做任何修改
Out[3]: {'k1': 1, 'k2': 3, 'k3': 2}
In[4]: sorted(dic.items())[0]
Out[4]: ('k1', 1)
刘奇

Dictionary is unordered and cannot be sorted,
sorted is just a list of key-value pair tuples of sorted d.

迷茫

sorted(zip(d.keys(), d.values())) 可解

刘奇

Because dic is a dictionary and is unordered, the result printed out may be different each time

And sorted(dic.item()) defaults to the first value of each tuple for the generated tuples ('k1', 1), ('k2', 2), ('k3', 3) Sort, so the printed result is ('k1', 1)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template