I have the following data from a dictionary in python
.
The problem that I am facing is the empty string as key and value in the dictionary.
data = {'id': '213', 'first_name': 'john', 'last_name': 'doe', '': ''}
my goal is to delete the empty string key
and create a new dictionary without it
so I tried:
from copy import deepcopy
for x, y in data.items():
if x == "":
del data[x]
new_data = deepcopy(data)
print(new_data)
but for some reason, I am getting the following error
...
for x, y in data.items():
RuntimeError: dictionary changed size during iteration
am I missing something?
CodePudding user response:
Since you are already creating a deepcopy, you may benefit by simply iterating over the keys and removing the unnecessary keys with a if condition.
Try this -
new_dict = {k:v for k,v in data.items() if k!=''}
print(new_dict)
{'id': '213', 'first_name': 'john', 'last_name': 'doe'}
As the error trace mentions quite clearly, the reason for the error in the following code is because you are modifying the dictionary during iteration.
for x, y in data.items():
if x == "":
del data[x] #<----
Instead, as mentioned by some other excellent answers (@tituszban), you should just use del data['']
directly.
CodePudding user response:
You cannot delete an item while iterating over it. But why would you? You know exactly the key you want to remove:
del data[""]
This will modify data
in place. If you want to keep the original dictionary, and create a new one without the key, see @Akshay Sehgal's answer
CodePudding user response:
The error is pretty straightforward: you cannot remove elements from a dictionary (or collection in general) while iterating on it.
A better approach might be to store which items you want to delete elsewhere, and then delete them all after the iteration, instead of trying to modify the dict in the iteration itself.
In particular, for your case you can simply do something like this, which will remove the key from the dict if it exists:
del data[""]
Instead of iterating over the whole dictionary, since by definition a dictionary can have at most one entry for any key.
CodePudding user response:
To extend hoodakaushal answer you can try doing it like
from copy import deepcopy
to_delete =[]
for x, y in data.items():
if x == "":
to_delete.append(x)
for key in to_delete:
del data[key]
new_data = deepcopy(data)
print(new_data)
CodePudding user response:
You can try also like this if want to extract data from dictionary
data = {'id': '213', 'first_name': 'john', 'last_name': 'doe', '': ''}
for i, j in data.items():
if i and j != "":
print(i, " ", j) # You can add String comment
print(i, j) #additional example without add comment