d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
Python如何认识到它只需要从字典中读取密钥?key是一个特殊的关键字,还是仅仅是一个变量?
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
Python如何认识到它只需要从字典中读取密钥?key是一个特殊的关键字,还是仅仅是一个变量?
当前回答
让我们开门见山。如果单词key只是一个变量,正如您所提到的,那么需要注意的是,当您在字典上运行“FOR LOOP”时,它只运行“key”,而忽略“value”。
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print (key, 'corresponds to', d[key])
不妨尝试一下:
d = {'x': 1, 'y': 2, 'z': 3}
for i in d:
print (i, 'corresponds to', d[i])
但如果使用以下函数:
d = {'x': 1, 'y': 2, 'z': 3}
print(d.keys())
在上面的例子中,keys不是一个变量,而是一个函数。
其他回答
要迭代键,使用my_dict.keys()会更慢,但效果更好。如果您尝试这样做:
for key in my_dict:
my_dict[key+"-1"] = my_dict[key]-1
它会创建一个运行时错误,因为在程序运行时您正在更改密钥。如果您绝对希望减少时间,请以my_dict方式使用for键,但您已收到警告。
如果您正在寻找清晰直观的示例:
cat = {'name': 'Snowy', 'color': 'White' ,'age': 14}
for key , value in cat.items():
print(key, ': ', value)
结果:
name: Snowy
color: White
age: 14
使用for..遍历字典时。。在..中-语法,它总是在键上迭代(值可以使用dictionary[key]访问)。
要迭代键值对,请使用以下命令:
对于Python 2中dict.iteritems()中的k,v对于Python 3中dict.items()中的k,v
您可以在GitHub上检查CPython的dicttype的实现。这是实现dict迭代器的方法的签名:
_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
PyObject **pvalue, Py_hash_t *phash)
CPython dictobject.c
key只是一个变量。
对于Python2.X:
>>> d = {'x': 1, 'y': 2, 'z': 3}
>>> for my_var in d:
>>> print my_var, 'corresponds to', d[my_var]
x corresponds to 1
y corresponds to 2
z corresponds to 3
…或更好,
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.iteritems():
print the_key, 'corresponds to', the_value
对于Python3.X:
d = {'x': 1, 'y': 2, 'z': 3}
for the_key, the_value in d.items():
print(the_key, 'corresponds to', the_value)