Comment puis-je supprimer une clé d'un dictionnaire Python

Mots clés : pythondictionarydata-structuresunsetpython

meilleur 4 Réponses Comment puis-je supprimer une clé d'un dictionnaire Python

vote vote

95

my_dict.pop('key', None) 
del my_dict['key'] 
vote vote

88

if 'key' in my_dict: del my_dict['key'] 
try:     del my_dict['key'] except KeyError:     pass 
vote vote

76

>>> 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 
>>> 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 
vote vote

61

myDict = {'a':1,'b':2,'c':3,'d':4} map(myDict.pop, ['a','c']) # The list of keys to remove >>> myDict {'b': 2, 'd': 4} 
map(lambda x: myDict.pop(x,None), ['a', 'c', 'e']) [1, 3, None] # pop returns >>> myDict {'b': 2, 'd': 4} 
[myDict.pop(x, None) for x in ['a', 'c', 'e']] 

Questions similaires