【发布时间】:2015-04-04 01:19:52
【问题描述】:
我创建了一个字典 a 并尝试使用方法 keys() 来返回它的键。下面是我得到的。我注意到keys() 的输出不是按字母顺序或字典中的原始顺序。
a
Out[1]: {1: 'JAN', 2: 'FEB', 3: 'MAR', 'APR': 4, 'MAY': 5}
a.keys()
Out[2]: ['APR', 1, 2, 3, 'MAY']
任何人都可以帮助我理解为什么会发生这种情况。以及这里使用的 order keys() 是什么?
【问题讨论】:
-
根本没有顺序....那是因为python字典不是按键排序的...你第一次很幸运。 :p
-
因为不是,所以需要排序
>>> a={1: 'JAN', 2: 'FEB', 3: 'MAR', 'APR': 4, 'MAY': 5} >>> sorted(a.keys()) [1, 2, 3, 'APR', 'MAY'] -
@littlejoshua 字典没有排序:docs.python.org/2/tutorial/datastructures.html
the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it) -
改用ordereddict。
标签: python dictionary