To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.
To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():
my_dict.pop('key', None)
This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.
To delete a key that is guaranteed to exist, you can also use
del my_dict['key']
This will raise a KeyError if the key is not in the dictionary.
Specifically to answer "is there a one line way of doing this?"
if 'key' in my_dict: del my_dict['key']
...well, you asked ;-)
You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that 'key' may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of
try:
del my_dict['key']
except KeyError:
pass
which, of course, is definitely not a one-liner.
python - Delete an element from a dictionary - Stack Overflow
Python - How to delete an item/value from a key in a dictionary?
Removing key value pairs from a dictionary
Is there a way to remove items/keys from a dict in a loop?
Videos
The del statement removes an element:
del d[key]
Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:
def removekey(d, key):
r = dict(d)
del r[key]
return r
The dict() constructor makes a shallow copy. To make a deep copy, see the copy module.
Note that making a copy for every dict del/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).
pop mutates the dictionary.
>>> lol = {"hello": "gdbye"}
>>> lol.pop("hello")
'gdbye'
>>> lol
{}
If you want to keep the original you could just copy it.
I know that I can delete a key using del but I don't know if I can remove an item and leave the key as it is.
Hello, I really can't figure out this assignment. Can anyone help? I posted my code at the bottom, and I know it doesn't make sense but i've tried so many random things at this point.
​
#Write a function called clean_data. clean_data takes one
#parameter, a dictionary. The dictionary represents the
#observed rainfall in inches on a particular calendar day
#at a particular location. However, the data has some
#errors.
#
#clean_data should delete any key-value pair where the value
#has any of the following issues:
#
# - the type is not an integer or a float. Even if the value
# is a string that could be converted to an integer (e.g.
# "5") it should be deleted.
# - the value is less than 0: it's impossible to have a
# negative rainfall number, so this must be bad data.
# - the value is greater than 100: the world record for
# rainfall in a day was 71.8 inches
#
#Return the dictionary when you're done making your changes.
#
#Remember, the keyword del deletes items from lists
#and dictionaries. For example, to remove the key "key!" from
#the dictionary my_dict, you would write: del my_dict["key!"]
#Or, if the key was the variable my_key, you would write:
#del my_dict[my_key]
#
#Hint: If you try to delete items from the dictionary while
#looping through the dictionary, you'll run into problems!
#We should never change the number if items in a list or
#dictionary while looping through those items. Think about
#what you could do to keep track of which keys should be
#deleted so you can delete them after the loop is done.
#
#Hint 2: To check if a variable is an integer, use
#type(the_variable) == int. To check if a variable is a float,
#use type(the_variable) == float.
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print (although the order of the keys may vary):
#{"20190101": 5, "20190103": 7.5, "20190104": 0, "20190107": 1}
rainfall = {"20190101": 5, "20190102": "6", "20190103": 7.5,
"20190104": 0, "20190105": -7, "20190106": 102,
"20190107": 1}
print(clean_data(rainfall))
-----------------------------------------------------------------------
This is my current code, which I know doesn't make sense but i've tried a million different random things at this point:
def clean_data(dictionary):
deleted_pairs=[]
items_as_list = list(dictionary.items())
for pair in items_as_list:
if type(pair[1])!= int and type(pair[1]) != float: deleted_pairs.append(pair)
if (type(pair[1]) == int or type(pair[1]) == float) and (pair[1]<0 or pair[1]>100):
deleted_pairs.append(pair)
for pair in deleted_pairs:
if pair[0] in items_as_list:
del dictionary[pair]return dictionary
When I try to do this I get an error saying that the size of the dict has changed during iteration. Is it possible to achieve this without creating another dict?
Thanks!