字典 .title() 中的 Python 字典

标签 python dictionary for-loop nested

我只想国家和资本化的值(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/

相关文章:

python - python中的聚类、相异度和距离是什么?

Python:如何将列表/数组/pd.Series中的零值设置为下一个非零值?

python - 许多for在python生成器中的一行中

arrays - bash-调用jq会生成语法错误和INVALID_CHARACTER消息

python - 当我运行测试时,django 如何重新定义 DJANGO_SETTINGS_MODULE?

Python ECDSA,用曲线 secp224k1 用私钥签名

windows-phone-7 - 将地理坐标分配给图钉

python - 数据库速度与静态字典速度的模型

javascript - Flask、python字典转highcharts JS图

javascript - 如何在javascript中的for循环中显示对象值