【问题标题】:Python dictionary inside a dictionary .title()字典中的 Python 字典 .title()
【发布时间】: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']strlist 进行比较,而key == 'country'strstr 进行比较

标签: python dictionary for-loop nested


【解决方案1】:

改变

if extras['country']:

if key == 'country':

【讨论】:

    【解决方案2】:

    我刚刚尝试了上面的答案,它似乎在 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']。
    猜你喜欢
    • 2012-01-22
    • 1970-01-01
    • 2011-05-18
    • 2014-10-15
    • 1970-01-01
    • 2017-05-05
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多