【问题标题】:confused about dictionary created variables对字典创建的变量感到困惑
【发布时间】: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


【解决方案1】:

在您的情况下,states.items() 迭代键值对,例如(“俄勒冈”,“或”)。 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)

【讨论】:

  • 所以你的意思是城市中的缩写是州字典中的缩写的结果?所以就像:city[OR],求 OR 的值?这就是它发生 keyerror 的原因,因为 states dict 中的 state 不在 city dict 中,无论是 key 还是 value。我的理解正确吗? @Bram Vanroy
  • 是的,完全正确。但是abbrev in cities 只检查该值是否在字典中作为键。它不检查它是否在值中。如果你想检查它是否是一个值,你可以做abbrev in cities.values()
  • 还有一个问题:如果我在 city.values() 中使用 abbrev,那么它将返回键而不是值,对吗? @Bram Vanroy
  • ...没有。cities.values():获取cities.keys():获取密钥。 cities.items() 获取键值对。
猜你喜欢
  • 1970-01-01
  • 2017-11-11
  • 2018-06-15
  • 2018-04-25
  • 1970-01-01
  • 2021-09-01
  • 2017-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多