Python字典中的嵌套字典 .title()

3

我只想将国家和值的首字母大写。

这是我的完整代码:

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

Hope that i am clear.


2
看起来你可能需要将 if extras['country']: 改为 if key == 'country': - Grant Williams
if extras['country'] 只是检查该键是否存在,而不是您当前正在迭代该键。 - Grant Williams
@GrantWilliams 没错!我尝试过了,但是我写成了 if key == ['country'] 就不行……但是如果写成 if key == 'country' 就可以了……这是为什么呢?感谢你的帮助! - Sea Wolf
1
@SeaWolf key == ['country'] 是将一个 str 与一个 list 进行比较,而 key == 'country' 是将一个 str 与另一个 str 进行比较。 - Wondercricket
2个回答

2

更改

if extras['country']:

为了

if key == 'country':

0

我刚刚尝试了上面的答案,它似乎在Python 2.7.14中可以工作(别问为什么...)

for city, extras in cities.items():
    print("\nInfo about the city " + city.title() + ":")
    for key, value in extras.items():
        try:
            if key == 'country':
                print(key.capitalize() + ": " + value.title())
            else:
                print(key.capitalize() + ": " + value)
        except(TypeError, AttributeError):
            print(key.capitalize() + ": " + str(value))

我得到了输出

Info about the city Berlin:
Country: Germany
Fact: once had a wall splitting west from east (or north from south)
Population: 25000000

Info about the city Rotterdam:
Country: Netherlands
Fact: is my home town
Population: 6000000

Info about the city Orlando:
Country: United States
Fact: is big
Population: 150000000

这不是你所希望实现的吗?


是的,正确的答案已经被编辑了。现在它可以工作了!但我不知道 if key == ['country'] 的区别是什么。 - Sea Wolf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接