I'm trying to read in a bunch of data from text files to a dictionary, and I've made a couple of small typos which end up creating new key/value pairs and breaking the program (which can be annoying and a pain to debug).
This got me wondering if there is a way to create a dictionary to which no keys can be added or removed after the initial declaration. This strikes me as something that must exist but I can't find an example of it; does anyone know of something that would fit the bill?
def change_key(dictionary, key, new_value):
a = dictionary.__len__()
dictionary[key] = new_value
if dictionary.__len__() != a:
raise ValueError("new key added")
What I'm looking for is a more elegant implementation of the code above that is:
not a massive mess of code
capable of dealing with things like appending to a nested list or adding to a nested dict
reasonably efficient