Python字典查询

时间:2016-12-22 19:27:07

标签: python dictionary

这是来自LPTHW的代码:

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'

print '-' * 10
print "NY State has: ", cities['NY']
print "OR State has: ", cities['OR']

print '-' * 10
print "Michigan's abbreviation is: ", states['Michigan']
print "Florida's abbreviation is: ", states['Florida']

print '-' * 10
print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]

print '-' * 10
for state, abbrev in states.items():
    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():
    print "%s state is abbreviated %s and has city %s" % (
        state, abbrev, cities[abbrev])

print '-' * 10
state = states.get('Texas')

if not state:
    print "Sorry, no Texas."

city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city

我想要了解的是Python如何将一个字典与另一个字典链接起来?在代码中。

print "Michigan has: ", cities[states['Michigan']]
print "Florida has: ", cities[states['Florida']]`

python是否会从后向读取它?它会首先查看州和找到密歇根州,然后找到它的价值,然后最终使用这个值将会看到来自州的价值是关键并从城市打印出钥匙价值的城市吗?为什么它不只是从城市打印出密钥(MI)?

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

Python不链接词典。它在cities[states['Michigan']]行中的作用首先将states['Michigan']评估为'Michigan'字典states'MI'的值。之后表达式看起来像cities['MI']。然后它从'MI'字典(cities)将其评估为'Detroit'的值。

答案 1 :(得分:1)

它不是向后解​​析,而是按照最内层表达的顺序 - >最外层的表达。

因此,对于cities[states['Michigan']],它将

  1. 查看cities
  2. 认识到需要解决states['Michigan']
  3. 查看states
  4. 查找states['Michigan']
  5. states['Michigan']cities
  6. 的返回值
  7. 现在它可以解析cities[states['Michigan']]

答案 2 :(得分:1)

这是它的工作原理,

1 - 首先查找

的值
states['Michigan']

=“MI”

2 - 然后取最后一个值并将其放入城市dict

cities['MI']