Crossin的编程教室

标题: 求助!怎样理解字典的输出结果 [打印本页]

作者: hunsjie    时间: 2013-11-20 14:37
标题: 求助!怎样理解字典的输出结果
代码:
# create a mapping of state to abbreviation
states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI'
}

# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
    print "%s is abbreviated %s" % (state, abbrev)

结果:
California is abbreviated CAMichigan is abbreviated MINew York is abbreviated NYFlorida is abbreviated FLOregon is abbreviated OR

为何输出的顺序并不是按字典顺序呢?还是输出有某个规则?

作者: crossin先生    时间: 2013-11-20 19:54
字典是无序的,这点和list是不一样的。所以字典也不能直接用索引访问,只能通过key来访问




欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/) Powered by Discuz! X2.5