-2

having some pains with the following code in Python:

dict_items = sample_dict.items()
sample_dict.clear()

where sample_dict is a dictionary from int to dict.

I am trying to save memory by clearing my dictionary (after this code is run I never use this dictionary to access values, I just care about the k,v pairs stored in the dict), but after dict.clear() is run, dict_items gets nuked. Running print(dict_items) yields the following:

[key1:{},key2:{}...]

Not very familiar with how memory is stored in python - how can I keep dict_items intact after running sample_dict.clear()?

Thornside
  • 9
  • 1
  • 1
    Do not use `dict` as variable name – balderman May 06 '22 at 18:48
  • 1
    How big is `dict` to begin with? Python does automatic memory management and garbage collection, so there's not really a need to do it manually unless you're dealing with a gigantic data structure. And even then, I'd leave it to Python 99% of the time. – MattDMo May 06 '22 at 18:48
  • 2
    `dict.items()` is an iterator over the contents of the dict. If the dict has no more contents, then nothing will be iterated. – jasonharper May 06 '22 at 18:48
  • 3
    I suppose you could consume the items into a list before clearing the dictionary, but then what memory have you saved? – jonrsharpe May 06 '22 at 18:50
  • 2
    Of course it does, `dict.items()` returns a *view* of the dictionaries underlying data. This is [clearly documented](https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects) – juanpa.arrivillaga May 06 '22 at 18:54
  • 3
    "Not very familiar with how memory is stored in python - how can I keep dict_items intact after running sample_dict.clear()?" You can't. But what would be the point? That would still use up memory. Just keep the `dict` around. I suppose, you could create a `list` out of the `items()`, so `dict_items = list(sample_dict.items())` but I doubt that will save you much memory. Is memory actually an issue fo ryou? – juanpa.arrivillaga May 06 '22 at 18:55
  • @jasonharper it is not an iterator, actually. Try it: `next(sample_dict.items())` – juanpa.arrivillaga May 06 '22 at 18:56
  • 3
    *"after this code is run I never use this dictionary to access values, I just care about the k,v pairs stored in the dict"* — Then just keep the dict as is. It's much more versatile than a list of tuples, and can be iterated as a list of tuples any time you need it. – deceze May 06 '22 at 19:05
  • 1
    Does this answer your question? [What are dictionary view objects?](https://stackoverflow.com/questions/8957750/what-are-dictionary-view-objects) I think understanding first how the `.items` work would clear up some misconceptions on what happens on `.clear` and "saving memory". – Gino Mempin May 07 '22 at 08:14

0 Answers0