【发布时间】:2018-10-24 14:32:06
【问题描述】:
# -*- 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 & city[abbrev])?
我的猜测是“缩写”被使用了两次,一次在州字典中,一次在城市字典中。那么 city[abbrev] 的意思是返回每对事物的第二个值?有人可以确认我的猜测是否正确吗?
如果是这样,为什么我将城市[缩写] 更改为城市[州] 时会出现 keyerror?错误代码是:KeyError:'california'。它应该返回每对的第一个值。
我对它的工作原理感到困惑,你能帮我找到出路吗?
【问题讨论】:
-
该行使用
abbrev的值从先前定义的cities字典中获取值。 -
states的值是cities中的一个键。state不是cities中的键。
标签: python python-2.7 dictionary