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 dictionary: pop or del - Stack Overflow
python - Delete an element from a dictionary - Stack Overflow
How to delete from a deque in constant time without "pointers"?
There's a technique which I call 'lazy popping' which can help here.
The idea is that you don't delete immediately from the queue. Rather, you leave deleted items in the queue, but mark them as deleted in another data structure -- usually a set. Whenever you have to pop an item to execute, keep popping until you reach an item that hasn't yet been deleted.
This gives you constant-time push, amortized constant-time pop (although you may pop multiple deleted items off the queue each time you pop an item to execute, each item only gets popped exactly once) , and constant-time deletion, which is better than what you can get by maintaining a list and deleting from start or middle.
In this case, you'd save the IDs of deleted items in the set. It looks like this (untested code):
import collections
class DeletableQueue:
def __init__(self):
self.deleted = set()
self.queue = collections.deque()
def push(self, item):
self.queue.append(item)
def pop(self):
# Precondition: there is at least one non-deleted item on the queue.
while id(q[0]) in deleted:
q[0].pop_left() # Discard an already-deleted item.
return q.pop_left() # Return the actual item to pop
def delete(self, item_to_delete):
self.deleted.add(id(item_to_delete)) More on reddit.com 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.