I was looking for a way to create multiple ad-hoc copies of a dictionary to hold some “evolutionary states”, with just slight generational deviations and found this little prototype-dict:
class ptdict(dict):
def asprototype(self, arg=None, **kwargs):
clone = self.__class__(self.copy())
if isinstance(arg, (dict, ptdict)):
clone.update(arg)
clone.update(self.__class__(kwargs))
return clone
Basically i want smth. like:
generation0 = dict(propertyA="X", propertyB="Y")
generations = [generation0]
while not endofevolution():
# prev. generation = template for next generation:
nextgen = generations[-1].mutate(propertyB="Z", propertyC="NEW")
generations.append(nextgen)
and so on.
I was wondering, if the author of this class and me were missing something, because i just can’t imagine, that there’s no standard-library approach for this. But neither the collections nor the itertools seemed to provide a similar simple approach.
Can something like this be accomplished with itertools.tee?
Update:
It’s not a question of copy & update, because, that’s exactly what this ptdict is doing. But using update doesn’t return a dict, which ptdict does, so i can for example chain results or do in-place tests, which would enhance readability quite a bit. (My provided example is maybe a bit to trivial, but i didn’t want to confuse with big matrices.)
I apologise for not having been precise enough. Maybe the following example clarifies why i’m interested in getting a dictionary with a single copy/update-step:
nextgen = nextgen.mutate(inject_mutagen("A")) if nextgen.mutate(inject_mutagen("A")).get("alive") else nextgen.mutate(inject_mutagen("C"))
I guess you’re looking for something like this:
See
dict