区分大小写和字典

问题描述 投票:0回答:2

我正在尝试创建一个可以为相应数据调用的字典。我的问题是我必须在用户输入中考虑区分大小写。字典存储在函数 main() 中。这个程序的目标是让用户能够使用函数的输出(在本例中存储在“dict1”中)并输入键来获取相应的数据。这是我现在程序的简化版本。

由于地方限制,用户必须使用Shell来赋值变量和c

def main(data_source_file):

    ### For sake of brevity, imagine I extract the data from the file and convert to a dict
    ### The final output is below

    dict1 = {'Africa': [1,2], 'Asia': [3,4], 'Americas', [5,6]}
    return dict1

>>> dict1 = main('datafile')
>>> dict1["Africa"]
[1,2]
>>> dict1["AFRICA"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'AFRICA'

我熟悉字符串和列表中大写的概念,但是我不确定如何将其应用于用户的键输入。

我的第一个想法是批准的条目列表,例如。 ["AFRICA","africa","Africa", (ect)] 但是我希望能够解释诸如“AFriCA”之类的输入,因此为每个字典键编写批准的列表将花费太长时间。

python string function dictionary capitalization
2个回答
2
投票

一般来说,如果有效输入的可能性太多,最简单和最清晰的方法通常是在比较输入之前normalize输入。

所以对于这个问题,我首先想到的是确保key在字典中全部小写,然后在查字典之前将用户输入小写。

对于严肃的解决方案,还要记住有一些奇怪的例外——在某些语言中,转换大小写有时会改变字母,而一些小写字母根本没有大写字母!所以小写比大写更健壮,但我们真正想要的想法的名字叫做“大小写折叠”。

您可以在这些问题+答案中阅读更多相关信息,以及如何在 Python 中实际执行此操作:

如何在 Python 中小写字符串?

如何进行不区分大小写的字符串比较?


0
投票

解决这个问题的方法是分别使用“lower()”或“upper()”函数将字典键存储为单字母或大写字母。

def main(data_source_file):

    ### For sake of brevity, imagine I extract the data from the file and convert to a dict
    ### The final output is below

    dict1 = {'Africa'.lower(): [1,2], 'Asia'.lower(): [3,4], 'Americas'.lower(): [5,6]}
    return dict1

dict1 = main('datafile')
print(dict1["Africa".lower()])

希望对您有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.