我只想国家和资本化的值(value)。
这是我的完整代码:
cities = {
'rotterdam': {
'country': 'netherlands',
'population': 6000000,
'fact': 'is my home town',
},
'orlando': {
'country': 'united states',
'population': 150000000,
'fact': 'is big',
},
'berlin': {
'country': 'germany',
'population': 25000000,
'fact':
'once had a wall splitting west from east (or north from south)',
},
}
for city, extras in cities.items():
print("\nInfo about the city " + city.title() + ":")
for key, value in extras.items():
try:
if extras['country']:
print(key.capitalize() + ": " + value.title())
else:
print(key.capitalize() + ": " + value)
except(TypeError, AttributeError):
print(key.capitalize() + ": " + str(value))
从这部分的输出来看,这就是我想要的:
Info about the city Rotterdam:
Country: Netherlands
但我也明白了:
Fact: Is My Home Town
如何防止 ['fact'] 值中的每个单词都被大写,并且只有键和 ['country'] 值才使用 .title() 大写?
所以我得到:
Info about the city Rotterdam:
Country: Netherlands
Population: 6000000
Fact: Is my home town
希望我清楚。
最佳答案
改变
if extras['country']:
到
if key == 'country':
关于字典 .title() 中的 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49904121/