【问题标题】:Case Insensitive Dictionary Iteration不区分大小写的字典迭代
【发布时间】:2022-11-07 20:41:45
【问题描述】:

我有一本字典,其中有人们的名字作为键。每个名字都有一个大写的首字母(James、Ben、John 等)。

我使用列表推导来检查字符串中是否有任何键:

[val for key, val in name_dict.items() if key in new_message]

问题是有时名称出现在 new_message 中的首字母没有大写(james、ben、john 等)。我可以将这些变体添加到字典中,但这会涉及很多工作。

有没有一种简单的方法可以以不区分大小写的方式迭代字典键?

【问题讨论】:

  • if key.lower() == new_message.lower()?
  • == 在这里不起作用,if key.lower() in new_message.lower()

标签: python


【解决方案1】:

new_message 上使用title(),它会将字符串中的所有单词大写

new_message = 'James, ben, JOHN'
print(new_message.title()) # James, Ben, John

【讨论】:

  • keynew_message 上使用.lower() 会更好
  • 它将涵盖更多选项
  • @OmerDagry 字典仅包含已知(大写)格式的名称,没有必要。
猜你喜欢
  • 2020-02-18
  • 2018-12-30
  • 2017-12-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 2018-01-26
相关资源
最近更新 更多