python - 对字典创建的变量感到困惑
问题描述
# -*- 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])
我只想知道在有问题的行上,只输入了两个变量(州和缩写),为什么会引用三个变量(州和缩写和城市[缩写])?
我的猜测是“缩写”被使用了两次,一次在州字典中,一次在城市字典中。那么 city[abbrev] 的意思是返回每对事物的第二个值?有人可以确认我的猜测是否正确吗?
如果是这种情况,为什么我将城市[缩写]更改为城市[州]时会出现密钥错误?错误代码是:KeyError:'california'。它应该返回每对的第一个值。
我很困惑这是如何工作的,你能帮我找到出路吗?
解决方案
在您的情况下,states.items()
迭代键值对,例如('oregon','OR')。state
将是'oregon'
并且abbrev
将是'OR'
。什么cities[abbrev]
是'OR'
在字典中找到 的值cities
。在这种情况下'OR'
是'portland'
。
如果您尝试了一个不在字典键中的值,例如banana
,那么 Python 会抛出 a 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)
推荐阅读
- database - 基于变量名称的模式匹配以在 Postgres 查询中选择变量?
- r - 如何在 R 的数据框中使用 mutate 来根据第二列的值更新列
- laravel - 如何在 laravel 5.4 中使用存储库模式实现事件/侦听器
- pycharm - Pycharm 2019 中的 Jupyter 工作目录
- python - 获取最长重复字符串的索引
- python - 为什么我在 python 中使用梯度下降得到逻辑回归的负成本函数?
- php - Laravel bcrypt 密码在流明中不匹配
- python - 从 FFT 中获取幅度最高的频率
- html - 在 div 中垂直间隔项目(flexbox space-around 不起作用..)
- python - 我正在尝试制作一个“自上而下”的基于瓷砖的游戏。我不知道如何最初制作瓷砖地图以放置图像