0

I have the following code snippet:

 modelLite.environments = model.environments

            for k,v in modelLite.environments.iteritems():
                v.grid = dict(copy.deepcopy(v.grid))

model.environments is a dictionary mapping strings to Grid objects. (Grid is my custom class) Each Grid object contains a grid attribute, which is a default dict.

In modelLite, I am trying to convert each defaultDict grid attribute to its corresponding dict object.

However, what I find is that the defaultDict object in model.environments are also being cast to dict alongside those in modelLite, despite using copy.deepcopy.

Any advice?

MrD
  • 4,986
  • 11
  • 48
  • 90
  • If you don't want them to be converted to vanilla dictionaries, why `dict`? `deepcopy` will create a new `defaultdict` just fine, it's *your code* that then creates a regular dictionary from it. – jonrsharpe Jul 15 '18 at 12:07
  • I want those in modelLite to be, not those in model. The issue is both are being converted. – MrD Jul 15 '18 at 12:08
  • No, my code should only change those in modelLite, not model – MrD Jul 15 '18 at 12:08
  • 2
    But they're the *same object*. `modelLite.environments = model.environments` - assignment *does not* create a copy. `deepcopy` is working just fine here. – jonrsharpe Jul 15 '18 at 12:09
  • 1
    To expand on jonrsharpe’s comment, `model.environments` is an *object reference*, a way to refer to a particular object. `modelLite.environments = model.environments` simply creates another reference to that same object. You need a way to make a *copy* of the object. – Tom Zych Jul 15 '18 at 12:11

0 Answers0