Dan*_*Boy -3 python dictionary key-value
这更需要澄清:
如果我说:
for key, value in dictionary.iteritems():
Run Code Online (Sandbox Code Playgroud)
这实际上会给我键和值,而不是仅将每个键分配给"键"和"值"
这只是让我一直迷惑Python的东西吗?
出于示例的目的,以下两个是等效的:
for item in dictionary:
print(item, dictionary[item])
Run Code Online (Sandbox Code Playgroud)
for k, v in dictionary.items():
print(k, v)
Run Code Online (Sandbox Code Playgroud)
但是,在示例1中,您无法直接访问value项目本身,只能访问密钥,而在示例2中,您可以以.的形式访问它v.
>>> dictionary = {'a': 1, 'b': 2, 'c': 3}
>>> for item in dictionary:
... print(item, dictionary[item])
...
b 2
c 3
a 1
>>> for k, v in dictionary.items():
... print(k, v)
...
b 2
c 3
a 1
Run Code Online (Sandbox Code Playgroud)
当然k, v是任意的k,v可以是任何东西,例如:
>>> for abc, xyz in dictionary.items():
... print(abc, xyz)
...
b 2
c 3
a 1
Run Code Online (Sandbox Code Playgroud)