Reputation: 6994
I simply generate a list of python dictionaries, and then serialize it to json.
Basically my code is a loop where I do something like:
ls.append({..values..})
I don't change the dictionaries after this.
The question, is there a constant dictionary in python, obviously the point here is memory, since I know dictionary takes more memory than a list. I simply need the structure of {key:value}
for json, not the other features of the dictionary.
Just curious if I can optimize my code a bit.
Upvotes: 1
Views: 21948
Reputation: 6935
At its core, JSON is just a standardized way of converting more complex structures into plain text, in a way that any JSON-compatible application would understand. Because of this, the most time- and memory-efficient way of storing a non-changing, JSON-used object is to convert it to its JSON text form and store it in a string. That not only saves you from storing dictionaries in memory, but you don't need to do any more JSON conversions after that. You can just output that string to whatever application needs to receive the JSON object.
>>> import json
>>> testdict = {}
>>> testdict["pooh bear"] = "honey tree"
>>> jsonstr = json.dumps(testdict)
>>> jsonstr
'{"pooh bear": "honey tree"}'
As the comments have pointed out, Python does not have constants, nor does it have a more memory-constrained dictionary to my knowledge. The dictionary is implemented as a hash table, which is designed for very quick inserts and accesses; whenever you have a really fast data structure, your tradeoff is usually that it takes up a lot of memory. This is a persistent thing in most any data structure you can think of.
Upvotes: 2