Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary inside a dictionary .title()

I want just the country and the value capitalized.

This is my full code:

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))

From the output this part works, this is how i want it:

Info about the city Rotterdam:
Country: Netherlands

But i also get this:

Fact: Is My Home Town

How can i prevent every word in the value of ['fact']from being capitalized and have just the keys and only the ['country'] value capitalized using .title()?

so that i get:

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

Hope that i am clear.

like image 610
Sea Wolf Avatar asked Jun 13 '26 00:06

Sea Wolf


1 Answers

change

if extras['country']:

to

if key == 'country':
like image 196
fferri Avatar answered Jun 15 '26 12:06

fferri