【问题标题】:How can you find a value in a dictionary where the key contains a space?如何在键包含空格的字典中找到值?
【发布时间】:2021-09-29 00:35:59
【问题描述】:

我正在处理我无法更改的字典 - 所以很遗憾,删除空格不是一种选择。

我试图找出当键有空格时如何调用键的值。 这个字典中的键都是字符串。有些是“word1 word2”,其他实际上是句子。请参阅下面的示例。

示例:{'color banana': 'yellow', 'brand of car': 'mercedes benz', 'type': 'sale}

如何获得这样的键值?

提前感谢您的帮助!

【问题讨论】:

  • 似乎显而易见的答案就是像访问任何其他密钥一样访问它,例如通过example_dict['brand of car'];我在这里缺少一些微妙之处吗?

标签: python dictionary key whitespace key-value


【解决方案1】:

如果您要查找字典中包含空格的所有键,则可以使用:

example = {'colour banana': 'yellow', 'brand of car': 'mercedes benz', 'type': 'sale'}

print({k: v for k, v in example.items() if ' ' in k})

返回

{'colour banana': 'yellow', 'brand of car': 'mercedes benz'}

如果只是寻找价值的问题,那么空间无关紧要。你可以使用example['colour banana']

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多