# -*- 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])
我只想知道在可疑的行上,仅输入了两个变量(州和缩写),为什么可能要引用三个变量(州和缩写和城市[缩写])?
我的猜测是,“ abbrev”被使用两次,一次是在州字典中,一次是在城市字典中。那么,citys [abbrev]是指返回每个配对对象的第二个值吗?有人可以确认我的猜测是否正确吗?
如果是这种情况,为什么在将城市[abbrev]更改为城市[state]时会出现键盘错误?错误代码为:KeyError:“加利福尼亚”。它应该返回每对的第一个值。
我对它的工作方式感到困惑,请您帮我找到解决方法?
答案 0 :(得分:-1)
在您的情况下,states.items()
重复键-值对,例如(“ oregon”,“ OR”)。 state
将是'oregon'
,而abbrev
将是'OR'
。 cities[abbrev]
的作用是在字典'OR'
中找到cities
的值。对于'OR'
就是'portland'
。
如果您尝试的值不在词典的键中,例如banana
,然后Python会抛出KeyError
,因为值banana
不是该词典中的键。
要确保字典中存在键,可以使用in
运算符。
for state, abbrev in states.items():
# if the value of abbrev (e.g. 'OR') is a value in the cities dictionary
# we know that there is a city in this state. Print it.
if abbrev in cities:
print "%s state is abbreviated %s and has city %s" % (state, abbrev, cities[abbrev])
else:
print "%s is abbreviated %s" % (state, abbrev)