Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python字典查询_Python_Dictionary - Fatal编程技术网

Python字典查询

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 '-

这是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)的钥匙


谢谢你的帮助

Python不链接字典。它所做的是在
城市[州['Michigan']]
行中,它首先计算
州['Michigan']
字典(即
'MI'
)中的
'Michigan'
的值。在该表达式之后,看起来像城市['MI']。然后它计算出城市词典(底特律词典)中的
'MI'
值。

它的解析不是完全向后的,而是按照最里面的表达式->最外面的表达式的顺序

因此,对于城市[密歇根州],它将

  • 查看
    城市
  • 认识到它需要解析州['Michigan']
  • 查看
    状态
  • 查找[密歇根州]
  • 州['Michigan']
    到城市的返回值
  • 现在它可以解析城市[密歇根州]
  • 这就是它的工作原理

    1-它首先查找

    states['Michigan']
    
    =“米”

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

    cities['MI']
    

    好。。。是 啊你认为它还有什么其他的方法来计算这个表达式?是的,当然是这样的。你可以把它想象成,
    城市[州['Michigan']]
    ->
    城市['MI']
    ->
    ->
    'Detroit'
    。对不起,我一周前就开始学习了,所以对于某人来说,一个愚蠢的问题就是我在学习编码。太棒了!非常感谢你。