Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

python 字典如何判断指定的 key 是否存在的几种方式及性能对比

Python 笔记 Python 笔记


在 python 中,判断字典中指定的 key 是否存在有三种方式,if key in dctif key in dct.keys() 和 if dct.has_key(key),其中 key in dct 形式效率最快,推荐使用。

key in dct(推荐方式)

dct = {'knowledge': 18, "dict": 8}
if 'knowledge' in dct:
    print(dct['knowledge'])

key in dct.keys()

if 'knowledge' in dct.keys():
    print(dct['knowledge'])

dct.has_key(key)(python 2.2 及以前)

python 2.2 及之前的版本,字典提供了查询指定 key 是否存在的函数 has_key,但在 python 3 已经删除。

if dct.has_key('knowledge'):
    print(dct['knowledge'])

三种方式的效率对比

import time
from matplotlib import pyplot as plt

n = 10000
time1 = []
time2 = []
time3 = []
for n in range(100,10100,100):
    my_dict = {}
    for i in range(n):
        my_dict[i] = i

    start = time.time()
    for i in range(n):
        if i in my_dict.keys():
            pass
    end = time.time()
    print end - start
    time1.append(end - start)

    start = time.time()
    for i in range(n):
        if my_dict.has_key(i):
            pass
    end = time.time()
    print end - start
    time2.append(end - start)

    start = time.time()
    for i in range(n):
        if i in my_dict:
            pass
    end = time.time()
    print end - start
    time3.append(end - start)

t = range(100,10100,100)
plt.plot(t, time1, label='in keys()')
plt.plot(t, time2, label='has_key')
plt.plot(t, time3, label='in')
plt.legend()
plt.show()