Python将键随机排序
这让我很困惑:Python将键随机排序,python,dictionary,python-2.x,Python,Dictionary,Python 2.x,这让我很困惑: row = {'Item1':1, 'Item2':2, 'Item3':3} fieldnames = list(row.keys()) print(list(row)) fieldnames.append('Item4') print(list(row)) 输出 ['Item3', 'Item1', 'Item2'] ['Item3', 'Item1', 'Item2'] 再次运行时: ['Item3', 'Item2', 'Item1'] ['I
row = {'Item1':1, 'Item2':2, 'Item3':3}
fieldnames = list(row.keys())
print(list(row))
fieldnames.append('Item4')
print(list(row))
输出
['Item3', 'Item1', 'Item2']
['Item3', 'Item1', 'Item2']
再次运行时:
['Item3', 'Item2', 'Item1']
['Item3', 'Item2', 'Item1']
什么?keys()是否随机访问列表?有没有更好的方法来做我想做的事?(即按照dict键出现的顺序获取它们)根据Python文档: dictionary对象的keys()方法以任意顺序返回dictionary中使用的所有键的列表(如果要对其排序,只需对其应用sorted()函数即可)。
散列是随机的,因此顺序不同。它不是列表,字典没有顺序。您可能需要使用OrderedDict。您使用的Python版本是什么?使用3.x我得到了
['Item1','Item2','Item3']
我觉得自己很愚蠢的可能的副本。谢谢大家