775. Serialize a key-value store to a string and restore it
A store that lives in memory must survive restarts, so it needs to save its state as text and load it back exactly. The hard part is values whose characters look like your own format.
Write serialize(store) and deserialize(text). store is a dict whose keys are strings and whose values are one of: a string, an int, a bool, None, or a list whose items are any of these (lists may nest). serialize returns a single string. deserialize returns a dict equal to the original, with the same types (True must come back as True, not 1; '1' must come back as a string). Do not use json, pickle, repr, eval or ast.
Strings may contain any character, including quotes, commas, brackets, colons, digits and newlines.
def serialize(store)Example 1
Input: deserialize(serialize({'name': 'run:7', 'steps': 100, 'tags': ['a', ['b', 3]], 'done': False, 'note': None}))
Output: {'name': 'run:7', 'steps': 100, 'tags': ['a', ['b', 3]], 'done': False, 'note': None}
Example 2
Input: deserialize(serialize({}))
Output: {}
Constraints
- At most 10,000 keys.
- Lists nest at most 50 deep.
- Ints may be negative.
Hint 1
Test isinstance(v, bool) before isinstance(v, int).
Hint 2
Length-prefix strings instead of quoting and escaping them.
Hint 3
Have the decoder return (value, next_index).
Common mistakes
- Turning True into 1 or '1' into 1 on the way back.
- Splitting on a separator that can appear inside a string.
- Forgetting empty lists, empty strings or an empty store.
Understand the idea
Serialization formats are grammars. A good homemade format is unambiguous (every byte has one meaning), self-delimiting (length or count prefixes) and typed. Recursive descent parsing with a moving index is the simplest way to read nested data. This is what checkpointing code, caches and storage engines do under the hood.