python - Supprimer un élément d'un dictionnaire

Mots clés : pythondictionarydelpython

meilleur 5 Réponses python - Supprimer un élément d'un dictionnaire

vote vote

92

del d[key] 
def removekey(d, key):     r = dict(d)     del r[key]     return r 
vote vote

84

 >>> lol = {"hello": "gdbye"}  >>> lol.pop("hello")      'gdbye'  >>> lol      {} 
vote vote

72

>>> a {0: 'zero', 1: 'one', 2: 'two', 3: 'three'} >>> {i:a[i] for i in a if i!=0} {1: 'one', 2: 'two', 3: 'three'} 
vote vote

61

key_to_remove = "c" d = {"a": 1, "b": 2} del d[key_to_remove]  # Raises `KeyError: 'c'` 
key_to_remove = "c" d = {"a": 1, "b": 2} d.pop(key_to_remove)  # Raises `KeyError: 'c'` 
key_to_remove = "c" d = {"a": 1, "b": 2} try:     del d[key_to_remove] except KeyError as ex:     print("No such key: '%s'" % ex.message) 
key_to_remove = "c" d = {"a": 1, "b": 2} try:     d.pop(key_to_remove) except KeyError as ex:     print("No such key: '%s'" % ex.message) 
key_to_remove = "c" d = {"a": 1, "b": 2} if key_to_remove in d:     del d[key_to_remove] 
key_to_remove = "c" d = {"a": 1, "b": 2} if key_to_remove in d:     d.pop(key_to_remove) 
key_to_remove = "c" d = {"a": 1, "b": 2} d.pop(key_to_remove, None)  # No `KeyError` here 
def get_dict_wo_key(dictionary, key):     """Returns a **shallow** copy of the dictionary without a key."""     _dict = dictionary.copy()     _dict.pop(key, None)     return _dict   d = {"a": [1, 2, 3], "b": 2, "c": 3} key_to_remove = "c"  new_d = get_dict_wo_key(d, key_to_remove) print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3} print(new_d)  # {"a": [1, 2, 3], "b": 2} new_d["a"].append(100) print(d)  # {"a": [1, 2, 3, 100], "b": 2, "c": 3} print(new_d)  # {"a": [1, 2, 3, 100], "b": 2} new_d["b"] = 2222 print(d)  # {"a": [1, 2, 3, 100], "b": 2, "c": 3} print(new_d)  # {"a": [1, 2, 3, 100], "b": 2222} 
from copy import deepcopy   def get_dict_wo_key(dictionary, key):     """Returns a **deep** copy of the dictionary without a key."""     _dict = deepcopy(dictionary)     _dict.pop(key, None)     return _dict   d = {"a": [1, 2, 3], "b": 2, "c": 3} key_to_remove = "c"  new_d = get_dict_wo_key(d, key_to_remove) print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3} print(new_d)  # {"a": [1, 2, 3], "b": 2} new_d["a"].append(100) print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3} print(new_d)  # {"a": [1, 2, 3, 100], "b": 2} new_d["b"] = 2222 print(d)  # {"a": [1, 2, 3], "b": 2, "c": 3} print(new_d)  # {"a": [1, 2, 3, 100], "b": 2222} 
vote vote

56

del foo['bar'] 
>>> foo = {'bar': 'baz'} >>> fu = dict(foo) >>> del foo['bar'] >>> print foo {} >>> print fu {'bar': 'baz'} 
def minus_key(key, dictionary):     shallow_copy = dict(dictionary)     del shallow_copy[key]     return shallow_copy 

Questions similaires