Python 2.7.3错误排序dict

时间:2015-05-19 09:57:16

标签: python dictionary

我在使用Python 2.7.3获取有序的dict时遇到了麻烦。前两个示例的行为与预期的一样,第三个示例返回错误排序的dict,虽然逻辑是相同的(我尝试使用其他值而不是' *'并得到相同的结果):

Python 2.7.3 (default, Dec 18 2014, 19:10:20) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d={}
>>> for k in [1, 6, 5, 2]:
...   d[k]='*'
... 
>>> d
{1: '*', 2: '*', 5: '*', 6: '*'}
>>> 
>>> d={}
>>> for k in [1, 2, 5, 6]:
...   d[k]='*'
... 
>>> d
{1: '*', 2: '*', 5: '*', 6: '*'}
>>> 
>>> d={}
>>> for k in [1001, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 4001, 4002, 4003, 4005, 4006, 4007, 4008, 4010, 4011, 4012, 4013, 4241, 5001, 5002, 5003, 5004, 5005, 5006, 5007, 5008, 5009, 5010, 5011, 5012, 5013, 5014, 5015, 5016, 5017, 5018, 5024, 5025, 5030, 5031, 5032, 5033, 5034, 5035, 5036, 5037, 5038, 5039, 5040, 5041, 5241]:
...   d[k]='*'
... 
>>> d
{5035: '*', 5001: '*', 5002: '*', 5003: '*', 5004: '*', 5005: '*', 5006: '*', 5007: '*', 5008: '*', 4241: '*', 5010: '*', 5011: '*', 5012: '*', 5013: '*', 5014: '*', 5015: '*', 5016: '*', 5017: '*', 5018: '*', 5024: '*', 4001: '*', 4002: '*', 4003: '*', 4005: '*', 4006: '*', 4007: '*', 4008: '*', 5033: '*', 4010: '*', 4011: '*', 4012: '*', 4013: '*', 5038: '*', 5039: '*', 5040: '*', 5041: '*', 3001: '*', 3002: '*', 3003: '*', 3004: '*', 3005: '*', 3006: '*', 3007: '*', 3008: '*', 3009: '*', 3010: '*', 5025: '*', 5036: '*', 2001: '*', 2002: '*', 2003: '*', 2004: '*', 2005: '*', 2006: '*', 2007: '*', 2008: '*', 2009: '*', 5037: '*', 5030: '*', 5009: '*', 1001: '*', 5031: '*', 5032: '*', 5241: '*', 5034: '*'}
>>> d.keys()
[5035, 5001, 5002, 5003, 5004, 5005, 5006, 5007, 5008, 4241, 5010, 5011, 5012, 5013, 5014, 5015, 5016, 5017, 5018, 5024, 4001, 4002, 4003, 4005, 4006, 4007, 4008, 5033, 4010, 4011, 4012, 4013, 5038, 5039, 5040, 5041, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 5025, 5036, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 5037, 5030, 5009, 1001, 5031, 5032, 5241, 5034]

这有什么理由吗? 谢谢, 帕特里克

1 个答案:

答案 0 :(得分:-1)

python中的

字典是无序对象。 如果你愿意,你可以使用有序的词典: OrderedDict