使用或不使用dict.keys()访问Python字典键 [英] Accessing Python dict keys with or without dict.keys()

查看:42
本文介绍了使用或不使用dict.keys()访问Python字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我使用 keys()方法访问 dict 键:

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?

推荐答案

尽管已经提到了这一点,但我想在这些讨论中添加一些确切的数字.所以我比较了:

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

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

使用了一个包含1000000项的字典(浮动键),而我使用了100次重复的 timeit .这些是结果:

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

显然,调用 dtest.keys()在Python 2.x中有一些缺点

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

这篇关于使用或不使用dict.keys()访问Python字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆