Python字典查询
这是LPTHW的代码:Python字典查询,python,dictionary,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 '-
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)的钥匙
谢谢你的帮助 Python不链接字典。它所做的是在
城市[州['Michigan']]
行中,它首先计算州['Michigan']
到州
字典(即'MI'
)中的'Michigan'
的值。在该表达式之后,看起来像城市['MI']。然后它计算出城市词典(底特律词典)中的'MI'
值。它的解析不是完全向后的,而是按照最里面的表达式->最外面的表达式的顺序
因此,对于城市[密歇根州],它将
城市
状态
州['Michigan']
到城市的返回值states['Michigan']
=“米”
2-然后取最后一个值并将其放入cities dict
cities['MI']
好。。。是 啊你认为它还有什么其他的方法来计算这个表达式?是的,当然是这样的。你可以把它想象成,
城市[州['Michigan']]
->城市['MI']
->->'Detroit'
。对不起,我一周前就开始学习了,所以对于某人来说,一个愚蠢的问题就是我在学习编码。太棒了!非常感谢你。