dict.keys()
Python 中字典(Dictionary) , keys() 函数返回一个字典所有的键。
Python2.x和Python3.x有所不同:
在python2.x中,dict.keys()返回一个列表
~ $ /usr/local/python2/bin/python
Python 2.7.15 (default, Feb 21 2019, 10:58:06)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data={'project': '4', 'put_zone': '12', 'system': '28'}
>>> data.keys()
['project', 'put_zone', 'system']
>>> type(data.keys())
<type 'list'>
在python3.x中,dict.keys()返回一个dict_keys对象,比起列表,这个对象的行为更像是集合set,而不是列表list。
~ $ /usr/local/python3/bin/python3
Python 3.7.2 (default, Feb 21 2019, 10:55:58)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> data={'project': '4', 'put_zone': '12', 'system': '28'}
>>> data.keys()
dict_keys(['project', 'put_zone', 'system'])
>>> type(data.keys())
<class 'dict_keys'>
这种情况会导致在for循环中对字典做增删时,导致运行时错误。
~ $ vi t.py
import os
data={'project': '4', 'put_zone': '12', 'system': '28'}
for x in data.keys():
print(x)
if x == 'system':
data.pop('system')
print(data.keys())
~ $ /usr/local/python2/bin/python t.py
project
put_zone
system
['project', 'put_zone']
~ $ /usr/local/python3/bin/python t.py
project
put_zone
system
Traceback (most recent call last):
File "t.py", line 4, in <module>
for x in data.keys():
RuntimeError: dictionary changed size during iteration
解决方案:list(dict.keys())
~ $ vi t.py
import os
data={'project': '4', 'put_zone': '12', 'system': '28'}
for x in list(data.keys()):
print(x)
if x == 'system':
data.pop('system')
print(data.keys())
~ $ /usr/local/python3/bin/python3 t.py
project
put_zone
system
dict_keys(['project', 'put_zone'])