迭代字典中的键和值

gm0*_*m03 3 python dictionary

如何访问字典的键和值并迭代 for 循环?

dictionary = {1: "one", 2: "two", 3: "three"}
Run Code Online (Sandbox Code Playgroud)

我的输出将是这样的:

1  one
2  two
3  three
Run Code Online (Sandbox Code Playgroud)

小智 9

您可以使用此代码片段。

dictionary = {1:"a", 2:"b", 3:"c"}

# To iterate over the keys
for key in dictionary.keys():  # or `for key in dictionary`
    print(key)

# To iterate over the values
for value in dictionary.values():
    print(value)

# To iterate both the keys and values
for key, value in dictionary.items():
    print(key, '\t', value)
Run Code Online (Sandbox Code Playgroud)