Python:get()中的字典

2024-06-28 20:08:56 发布

您现在位置:Python中文网/ 问答频道 /正文

第一个帖子! 我正在慢慢地用Python自动化那些枯燥的东西,只是在用get()方法和字典做一些实验(第5章)。我写了一小段代码,告诉我输入的国家的首都,或者,如果它不在我的字典里,首都“不可用”。你知道吗

但是,即使输入词典中包含的国家,也会出现“不可用”的回答。对这里发生的事情有什么见解吗?我试着在get()方法中使用字典,但没有找到多少解释这个问题的方法。代码如下:

capitals = {'Australia': 'Canberra', 'England': 'London', 'South Africa': 'Pretoria'}
print('Choose country')
country = input()
print('The capital of ' + country + ' is ' 
      + capitals.get(capitals[country], 'not available'))

Tags: 方法代码get字典国家事情country帖子
2条回答

get方法替换了__getitem__(通常通过括号表示法访问)。capitals.get(capitals[country], 'not available')实际上正在执行两个查找:

  1. capitals[country]找到首都,例如堪培拉。你知道吗
  2. capitals.get(...)然后查找首都的名称作为国家。很少有这种不会失败的情况。你知道吗

如果你查找一个不存在的国家,capitals[country]只会产生一个KeyError。你知道吗

你可能想做的是

capitals.get(country, 'not available')

您可能需要考虑的另一个问题是Python字典区分大小写。你可能想拿回Canberra,不管你是传入Australiaaustralia还是aUstrAlIA。执行此操作的标准方法是使字典的键全部为小写,然后使用小写或case-folded版本进行查找:

capitals = {'australia': 'Canberra', 'england': 'London', 'south africa': 'Pretoria'}
country = input('Choose country: ')
print('The capital of', country, 'is', capitals.get(country.casefold(), 'not available'))

注意,我将第一个print替换为input的参数,并删除了第二个print中的+运算符。你知道吗

下面是Synax for get()方法:

dict.get(key, default = None)

在你的字典里,键是“澳大利亚”。你知道吗

在代码中:

capitals.get(capitals[country], 'not available')

capitals[country]不是键,您需要像下面这样使用它:

capitals.get(country, 'not available')

相关问题 更多 >