# -*- coding: utf-8 -*-
states = {
'oregon': 'OR',
'florida': 'FL',
'california': 'CA',
'new york': 'NY',
'michigan': 'MI'
}
cities = {
'CA': 'san francisco',
'MI': 'detroit',
'FL': 'jacksonville'
}
cities['NY'] = 'new york'
cities['OR'] = 'portland'
for state, abbrev in states.items(): # add two variables
print "%s is abbreviated %s" % (state, abbrev)
print '-' * 10
for abbrev, city in cities.items():
print "%s has the city %s" % (abbrev, city)
print '-' * 10
for state, abbrev in states.items(): # this is what i'm confusing about
print "%s state is abbreviated %s and has city %s" % (state, abbrev, cities[abbrev])
我只想知道在有问题的一行,只有两个变量输入(state&abbrev),为什么会有三个变量引用(state&abbrev&cities[abbrev])?你知道吗
我猜“abbrev”被用了两次,一次在states dict中,一次在cities dict中。那么cities[abbrev]的意思是返回每个成对事物的第二个值?有人能确认一下我的猜测是否正确吗?你知道吗
如果是这样的话,为什么当我将cities[abbrev]更改为cities[state]时会出现keyerror?错误代码是:KeyError:'california'。它应该返回每对的第一个值。你知道吗
我不知道这是怎么回事,你能帮我找个出路吗?你知道吗
在您的例子中,
states.items()
迭代键值对,例如('oregon','OR')。state
将是'oregon'
,abbrev
将是'OR'
。cities[abbrev]
所做的是在字典cities
中查找'OR'
的值。在'OR'
的情况下,即'portland'
。你知道吗如果尝试的值不在字典的键中,例如
banana
,那么Python会抛出一个KeyError
,因为值banana
不是该字典中的键。你知道吗要确保字典中存在键,可以使用
in
运算符。你知道吗相关问题 更多 >
编程相关推荐