简体   繁体   English

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

[英]confused about dictionary created variables

# -*- 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])

I just want to know on the questionable line, there are only two variables inputed(state & abbrev), why there could be three variables quoted(state & abbrev & cities[abbrev])? 我只想知道在可疑的行上,仅输入了两个变量(州和缩写),为什么可以引用三个变量(州和缩写和城市[缩写])?

My guess is that 'abbrev' is being used twice, once in states dict and once in cities dict. 我的猜测是,“ abbrev”被使用了两次,一次是在州命令中,一次是在城市命令中。 So cities[abbrev] means to return the second value of each paired things? 那么,citys [abbrev]是指返回每个配对对象的第二个值吗? Can someone please confirm if my guess is correct? 有人可以确认我的猜测是否正确吗?

If that's the case, why do I get a keyerror when I change cities[abbrev] into cities[state]? 如果是这样,当我将城市[缩写]转换为城市[州]时,为什么会出现键盘错误? The error code is: KeyError: 'california'. 错误代码为:KeyError:“加利福尼亚”。 It should return the first value of each pair. 它应该返回每对的第一个值。

I am confused on how this is working, can you please help me find a way out? 我对这是如何工作感到困惑,您能帮我找到出路吗?

In your case, states.items() iterates of the key-value pairs, eg ('oregon', 'OR'). 在您的情况下, states.items()会迭代键值对,例如('oregon','OR')。 state will be 'oregon' and abbrev will be 'OR' . state将为'oregon'abbrev将为'OR' What cities[abbrev] does is finding the value of 'OR' in the dictionary cities . 什么cities[abbrev]确实是发现价值'OR'字典中的cities In the case of 'OR' that is 'portland' . 'OR'的情况下是'portland'

If you tried a value that is not in the keys of the dictionary, eg banana , then Python would throw a KeyError because the value banana is not a key in that dictionary. 如果您尝试了不在字典键中的值,例如banana ,那么Python会抛出KeyError因为值banana不是该字典中的键。

To ensure that a key is present in a dictionary, you can use the in operator. 要确保字典中存在键,可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM