loadfn/dumpfn does not handle dict with integer keys
rkingsbury opened this issue · 2 comments
System
- Monty version: 2022.4.26
- Python version: 3.9.7
- OS version: Windows 11 / WSL 2 / Ubuntu
Summary
- When serializing and deserializing a
dict
whose keys are integers usingdumpfn
/loadfn
, the keys are converted to strings.
Example code
>>> d={1: "one",
2: "two",
}
>>> dumpfn(d, /some/path/d.json)
>>> d = loadfn(/some/path/d.json)
>>> d
{'1': "one",
'2': "two",
}
Suggested solution (if known)
Ideally the integer keys should be preserved before and after serialization, since the spirit of dumpfn
/ loadfn
is to make it possible to write objects to disk and recover them exactly. I'm not sure if there is some technical limitation that makes this impossible though.
This is not a monty problem, but rather a problem with the json spec itself (see https://www.json.org/json-en.html). For instance, try this monty-free method:
import json
j = json.dumps({1: "s"})
print(json.loads(j))
You will find that the integer has been converted to string.
But if you choose to do this in yaml, you will preserve the integer, whether using yaml parsers or using monty.
Basically loadfn and dumpfn delegates to the underlying spec parsers and only bypasses the need to provide a file-like object and infer the format from the extension. All limitations are the result of the spec/format.
OK, thanks for clarifying. I suspected something like that might be the case.