不区分大小写的字典 [英] Case insensitive dictionary
问题描述
我希望我的字典不区分大小写.
I'd like my dictionary to be case insensitive.
我有这个示例代码:
text = "practice changing the color"
words = {'color': 'colour',
'practice': 'practise'}
def replace(words,text):
keys = words.keys()
for i in keys:
text= text.replace(i ,words[i])
return text
text = replace(words,text)
print text
输出 = 练习改变颜色
Output = practise changing the colour
我想要另一个字符串,练习改变颜色"
,(其中 Color
以大写开头)也能给出相同的输出.
I'd like another string, "practice changing the Color"
, (where Color
starts with a capital) to also give the same output.
我相信有一种通用的方法可以使用mydictionary[key.lower()]
但我不确定如何最好地将它集成到我现有的代码中.(如果这仍然是一种合理、简单的方法).
I believe there is a general way to convert to lowercase using
mydictionary[key.lower()]
but I'm not sure how to best integrate this into my existing code. (If this would be a reasonable, simple approach anyway).
推荐答案
如果我理解正确,并且您想要一种以不区分大小写的方式键控字典的方法,一种方法是将 dict 子类化并重载 setter/吸气剂:
If I understand you correctly and you want a way to key dictionaries in a non case-sensitive fashion, one way would be to subclass dict and overload the setter / getter:
class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)
def __getitem__(self, key):
return super(CaseInsensitiveDict, self).__getitem__(key.lower())
这篇关于不区分大小写的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!