def eraseElement(d,k):if isinstance(d, dict):if k in d:d.pop(k)print(d)else:print("Cannot find matching key")else:print("Not able to delete")
exp = {'A':34, 'B':55, 'C':87}eraseElement(exp, 'C')
def execute():dic = {'a':1,'b':2}dic2 = remove_key_from_dict(dic, 'b')print(dict2) # {'a': 1}print(dict) # {'a':1,'b':2}
def remove_key_from_dict(dictionary_to_use, key_to_delete):copy_of_dict = dict(dictionary_to_use) # creating clone/copy of the dictionaryif key_to_delete in copy_of_dict : # checking given key is present in the dictionarydel copy_of_dict [key_to_delete] # deleting the key from the dictionaryreturn copy_of_dict # returning the final dictionary
也可以使用dict.pop()
d = {"a": 1, "b": 2}
res = d.pop("c") # No `KeyError` hereprint (res) # this line will not execute
或者更好的方法是
res = d.pop("c", "key not found")print (res) # key not foundprint (d) # {"a": 1, "b": 2}
res = d.pop("b", "key not found")print (res) # 2print (d) # {"a": 1}
yourList = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]resultList = [{'key':dic['key']} for dic in yourList if 'key' in dic]print(resultList)