字典里面的Python字典.title()

问题描述 投票:2回答:2

我只想要国家和价值资本。

这是我的完整代码:

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

希望我很清楚。

python dictionary for-loop nested
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

这不是你希望实现的吗?

© www.soinside.com 2019 - 2024. All rights reserved.