Python:比较字典键与字符串

Sca*_*ays 4 python string comparison dictionary

我正在尝试将字典中的键与 Python 中的字符串进行比较,但我找不到任何方法来做到这一点。假设我有:

\n\n
dict = {"a" : 1, "b" : 2}\n
Run Code Online (Sandbox Code Playgroud)\n\n

我想将字典中第一个索引的键(即“a”)与字符串进行比较。所以像这样:

\n\n
if \xc2\xb4Dictionary key\xc2\xb4 == "a":\n    return True\nelse:\n    return False\n
Run Code Online (Sandbox Code Playgroud)\n\n

有办法做到这一点吗?感谢我能得到的所有帮助。

\n

Ada*_*our 6

Python 字典具有和使用这些键访问的

您可以按如下方式访问键,您的字典键将存储在key变量中:

my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
    print(key)
Run Code Online (Sandbox Code Playgroud)

这将打印:

a
b
Run Code Online (Sandbox Code Playgroud)

然后您可以进行任何您想要的比较:

my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
    if key == "a":
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

可以改进为:

my_dict = {"a" : 1, "b" : 2}
print("a" in my_dict.keys())
Run Code Online (Sandbox Code Playgroud)

然后,您可以访问字典中每个键的值,如下所示:

my_dict = {"a" : 1, "b" : 2}
for key in my_dict:
    print(my_dict[key])
Run Code Online (Sandbox Code Playgroud)

这将打印:

1
2
Run Code Online (Sandbox Code Playgroud)

我建议您从官方 Python 文档中阅读有关字典的更多信息:https://docs.python.org/3.6/tutorial/datastructs.html#dictionaries