【发布时间】:2018-09-28 22:57:05
【问题描述】:
我只想要国家和资本化的价值。
这是我的完整代码:
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'] 值中的每个单词都被大写,并且只使用 .title() 将键和 ['country'] 值大写?
所以我得到:
Info about the city Rotterdam:
Country: Netherlands
Population: 6000000
Fact: Is my home town
希望我清楚。
【问题讨论】:
-
您可能需要将
if extras['country']:更改为if key == 'country': -
if extras['country']只是检查密钥是否存在,而不是您当前正在迭代该密钥。 -
@GrantWilliams 成功了!我试过了,但确实做到了:如果 key == ['country'] 它不起作用......但如果 key == 'country' 起作用......为什么会这样?感谢您的帮助!
-
@SeaWolf
key == ['country']将str与list进行比较,而key == 'country'将str与str进行比较
标签: python dictionary for-loop nested