d.pop(key)-- consider using this if you need the value for the item being deleted, and/or you want to specify a default value and don't want an exception raised if the key doesn't exist.
e.g.,value = d.pop(key, None)del key-- consider using this if you are certain that the key exists (or you expect an exception if it doesn't), and you don't need the value of the item being deleted.
e.g.,del key
From the official Python language documentation:
del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map.
pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
Answer from Wang Dingwei on Stack Overflowd.pop(key)-- consider using this if you need the value for the item being deleted, and/or you want to specify a default value and don't want an exception raised if the key doesn't exist.
e.g.,value = d.pop(key, None)del key-- consider using this if you are certain that the key exists (or you expect an exception if it doesn't), and you don't need the value of the item being deleted.
e.g.,del key
From the official Python language documentation:
del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map.
pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
pop returns the value of deleted key.
Basically, d.pop(key) evaluates as x = d[key]; del d[key]; return x.
- Use
popwhen you need to know the value of deleted key - Use
delotherwise
I have a dictionary and I wanted to remove one item and documentation mentioned that I can use:
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
del phonebook["John"]
print(phonebook)
or
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
phonebook.pop("John")
print(phonebook)
What's the difference between those two?
Pop vs Del
python - Is del or pop preferred when removing elements from dicts - Stack Overflow
Python dictionary: pop or del - Stack Overflow
python - Delete an element from a dictionary - Stack Overflow
You can use remove():
data = { "computers": [
{"Netbios_Name0": "apple1", "User_Domain0": "paradise", "User_Name0": "adam", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9058.1018"},
{"Netbios_Name0": "apple2", "User_Domain0": "paradise", "User_Name0": "lilith", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9040.1044"},
{"Netbios_Name0": "apple3", "User_Domain0": "paradise", "User_Name0": "eve", "SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9068.1026"}
]}
for item in list(data['computers']):
if 'apple2' in item['Netbios_Name0']:
data['computers'].remove(item)
data
Output:
{'computers': [{'Netbios_Name0': 'apple1',
'User_Domain0': 'paradise',
'User_Name0': 'adam',
'SMS_Installed_Sites0': 'heaven',
'Client_Version0': '5.00.9058.1018'},
{'Netbios_Name0': 'apple3',
'User_Domain0': 'paradise',
'User_Name0': 'eve',
'SMS_Installed_Sites0': 'heaven',
'Client_Version0': '5.00.9068.1026'}]}
You are iterating a list - you can pop from a list by index.
Never modify a lists length while while iterating: How to remove items from a list while iterating?
One way would be to store the indexes to be removed and remove them later:
data = { "computers": [
{"Netbios_Name0": "apple1", "User_Domain0": "paradise", "User_Name0": "adam",
"SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9058.1018"},
{"Netbios_Name0": "apple2", "User_Domain0": "paradise", "User_Name0": "lilith",
"SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9040.1044"},
{"Netbios_Name0": "apple3", "User_Domain0": "paradise", "User_Name0": "eve",
"SMS_Installed_Sites0": "heaven", "Client_Version0": "5.00.9068.1026"}
]}
to_delete = []
for idx, inner_dic in enumerate(data['computers']):
if "apple2" in inner_dic['Netbios_Name0']:
to_delete.append(idx)
# remove biggest to lowest indexes - removing does not influence the order
for idx in to_delete[::-1]:
data['computers'].pop(idx)
print(data)
Output:
{'computers':
[{'Netbios_Name0': 'apple1', 'User_Domain0': 'paradise', 'User_Name0': 'adam',
'SMS_Installed_Sites0': 'heaven', 'Client_Version0': '5.00.9058.1018'},
{'Netbios_Name0': 'apple3', 'User_Domain0': 'paradise', 'User_Name0': 'eve',
'SMS_Installed_Sites0': 'heaven', 'Client_Version0': '5.00.9068.1026'}]
}
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.