对字典创建的变量感到困惑吗

2024-10-02 10:30:56 发布

您现在位置: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])

我只想知道在有问题的一行,只有两个变量输入(state&abbrev),为什么会有三个变量引用(state&abbrev&cities[abbrev])?你知道吗

我猜“abbrev”被用了两次,一次在states dict中,一次在cities dict中。那么cities[abbrev]的意思是返回每个成对事物的第二个值?有人能确认一下我的猜测是否正确吗?你知道吗

如果是这样的话,为什么当我将cities[abbrev]更改为cities[state]时会出现keyerror?错误代码是:KeyError:'california'。它应该返回每对的第一个值。你知道吗

我不知道这是怎么回事,你能帮我找个出路吗?你知道吗


Tags: orincitynewforisitemsca
1条回答
网友
1楼 · 发布于 2024-10-02 10:30:56

在您的例子中,states.items()迭代键值对,例如('oregon','OR')。state将是'oregon'abbrev将是'OR'cities[abbrev]所做的是在字典cities中查找'OR'的值。在'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)

相关问题 更多 >

    热门问题