Accessing Python dict keys with or without dict.keys()

偶尔善良 提交于 2021-02-16 17:53:47

问题


Usually I access dict keys using keys() method:

d = {'a':1, 'b':2, 'c':3}

for k in d.keys(): print k

But sometimes I see this code:

for k in d: print k

Is this code correct? safe?


回答1:


Although this was already mentioned, I wanted to add some exact numbers to these discussion. So I compared:

def iter_dtest(dtest):
    for i in dtest:
        pass

and

def list_dtest(dtest):
    for i in dtest.keys():
        pass

A dictionary with 1 000 000 items was used (float keys) and I used timeit with 100 repetitions. These are the results:

Python 2.7.1:
iter_dtest: 3.92487884435s
list_dtest: 6.24848171448s

Python 3.2.1:
iter_dtest: 3.4850587113842555s
list_dtest: 3.535072302413432s

Obviously calling dtest.keys() has some downsides in Python 2.x




回答2:


To answer your explicit question, Yes, it is safe.

To answer the question you didn't know you had:

in python 2.x: dict.keys() returns a list of keys.

But doing for k in dict iterates over them.

Iterating is faster than constructing a list.

in python 3+ explicitly calling dict.keys() is not slower because it also returns an iterator.

Most dictionary needs can usually be solved by iterating over the items() instead of by keys in the following manner:

for k, v in dict.items():
    # k is the key
    # v is the value
    print '%s: %s' % (k, v)



回答3:


The second code example's behaviour is equal to calling .keys(), so yes, this is correct and safe.




回答4:


It's not the same.

for k in d: print k

does not create additional list, while

for k in d.keys(): print k

creates another list and then iterates over it

At least in Python 2. In Python 3 dict.keys() is an iterator.

So you can use either for k in d.iterkeys() or for k in d. Both lead to the same result.



来源:https://stackoverflow.com/questions/14730481/accessing-python-dict-keys-with-or-without-dict-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!