Build a Function to Serialize and Deserialize Nested Dictionaries with Custom Rules
Create a Python function to serialize a nested dictionary into a custom string format and another function to revert it back, handling complex nesting and type conversions.
Challenge prompt
Write two functions: serialize_dict and deserialize_dict. The serialize_dict function takes a nested dictionary and converts it into a custom string format where keys and values are joined by '=', pairs are separated by ';', and nested dictionaries are enclosed in parentheses, preserving nesting structure. The deserialize_dict function takes such a string and reconstructs the original dictionary, converting numeric strings back to integers or floats as appropriate. For example, given {'a': 1, 'b': {'c': 2, 'd': 3}}, serialize_dict should return 'a=1;b=(c=2;d=3)'. Then deserialize_dict('a=1;b=(c=2;d=3)') should return the original nested dictionary.
Guidance
- • Think recursively to handle arbitrarily deep nested dictionaries during serialization and deserialization.
- • Ensure to properly distinguish between string values and nested dictionaries during both operations.
- • Implement numeric detection to convert strings back to integers or floats in deserialization.
Hints
- • You can use recursion inside both functions to process nested dictionaries.
- • Use parentheses to mark boundaries of nested dictionaries during serialization.
- • When deserializing, carefully parse substrings to isolate keys and values and convert numeric strings.
Starter code
def serialize_dict(d):
# Implement this function
pass
def deserialize_dict(s):
# Implement this function
passExpected output
{"a": 1, "b": {"c": 2, "d": 3}}
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.