首页 > 解决方案 > 对字典创建的变量感到困惑

问题描述

# -*- 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'。它应该返回每对的第一个值。

我很困惑这是如何工作的,你能帮我找到出路吗?

标签: pythonpython-2.7dictionary

解决方案


在您的情况下,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)

推荐阅读