>>> import timeit>>> setup = "d = {i: i for i in range(100000)}"
>>> timeit.timeit("del d[3]", setup=setup, number=1)1.79e-06>>> timeit.timeit("d.pop(3)", setup=setup, number=1)2.09e-06>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)0.00786
但是当键不存在时,if key in my_dict: del my_dict[key]比my_dict.pop(key, None)略快。在try/except语句中,两者都比del快至少三倍:
>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)0.0229>>> timeit.timeit("d.pop('missing key', None)", setup=setup)0.0426>>> try_except = """... try:... del d['missing key']... except KeyError:... pass... """>>> timeit.timeit(try_except, setup=setup)0.133
test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}
# Printing dictionary before removalprint ("dictionary before performing remove is : " + str(test_dict))
# Using items() + dict comprehension to remove a dict. pair# removes vinodnew_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}
# Printing dictionary after removalprint ("dictionary after remove is : " + str(new_dict))
输出:
dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}