need:
There is a function whose argument is an empty dict. The dict is updated in the function, but the null key value pairs need to be filtered out.
Use del to delete dictionary key values
def f(dic): dic['a'] = 'aa' dic['b'] = 'aa' dic['c'] = '' dic['d'] = 'dd' print('Original Dictionary:', dic) ## Original dictionary: {'a': 'aa', 'b': 'aa', 'c': '', 'd': 'dd'} for k,v in list(()): if not v: del dic[k] d = {} f(d) print('From the empty key value:', d) ## After filtering the empty key value: {'a': 'aa', 'b': 'aa', 'd': 'dd'}
Notice:
Why use itlist(())
?
Because it cannot be modified while traversing the dictionary, otherwise a runtime error RuntimeError will be thrown. passlist(())
Create a copy of the key and you can safely delete it.
Attachment: Delete the key in the dict according to the situation
In Python, we can delete specific keys in dictionary (dict) based on different situations. This operation can help us dynamically adjust the content of the dictionary according to our needs.
Situation 1: Delete key-value pairs according to key names
If we know the name of the key to delete, we can directly use the del keyword to delete the specified key-value pair.
# Create a sample dictionarymy_dict = {'a': 1, 'b': 2, 'c': 3} # Delete key-value pairs with key 'b'del my_dict['b'] print(my_dict) # Output:{'a': 1, 'c': 3}
Situation 2: Delete key-value pairs based on key-value
Sometimes we may only know the value corresponding to the key to be deleted, but not the name of the key. At this time, you can find and delete key-value pairs that meet the criteria by traversing the dictionary.
# Create a sample dictionarymy_dict = {'a': 1, 'b': 2, 'c': 3} # Delete key-value pairs with a value of 2for key, value in my_dict.items(): if value == 2: del my_dict[key] break # Only delete the first key-value pair that meets the criteria print(my_dict) # Output:{'a': 1, 'c': 3}
Situation 3: Delete key-value pairs according to conditions
If the key-value pairs to be deleted need to meet certain conditions, we can use dictionary derivation to implement this function.
# Create a sample dictionarymy_dict = {'a': 1, 'b': 2, 'c': 3} # Delete key-value pairs with values greater than 1my_dict = {key: value for key, value in my_dict.items() if value <= 1} print(my_dict) # Output:{'a': 1}
The above is the method of deleting keys in the dictionary according to different situations. Delete according to key names, delete according to key values, and delete according to conditions, we can flexibly operate the dictionary content to meet the needs.
Summarize
This is the end of this article about how to delete the key of the python dictionary in situ. For more related content of deleting the key of the python dictionary in situ, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!