Python 3.x
from copy import deepcopy
my_dict = {'one': 1, 'two': 2}
new_dict_deepcopy = deepcopy(my_dict)
Without deepcopy, I am unable to remove the hostname dictionary from within my domain dictionary.
Without deepcopy I get the following error:
"RuntimeError: dictionary changed size during iteration"
...when I try to remove the desired element from my dictionary inside of another dictionary.
import socket
import xml.etree.ElementTree as ET
from copy import deepcopy
domain is a dictionary object
def remove_hostname(domain, hostname):
domain_copy = deepcopy(domain)
for domains, hosts in domain_copy.items():
for host, port in hosts.items():
if host == hostname:
del domain[domains][host]
return domain
Example output: [orginal]domains = {'localdomain': {'localhost': {'all': '4000'}}}
[new]domains = {'localdomain': {} }}
So what's going on here is I am iterating over a copy of a dictionary rather than iterating over the dictionary itself. With this method, you are able to remove elements as needed.