Box icon indicating copy to clipboard operation
Box copied to clipboard

Be able to initialize with a flattened dict?

Open dragonpaw opened this issue 5 years ago • 2 comments

I'm in a situation where I need to deal with some deeply nested structures, but I want to initialize them with dictionaries of dotted keys. So I'd ideally like to be able to do something like:

d = Box({'service.name': 'django', 'service.version': 2.2})
print(d.service.name) 
# Prints 'django'
print(d.service.keys())
# prints "dict_keys(['name', 'version'])"
print(d.to_dict())
# prints {'service': {'name': 'django', 'version': 2.2}}

Now, I can do this if I initialize the Box, then write to it as d.service.name = 'django', but it'd be nice to be able to unflatten the incoming dict somehow.

dragonpaw avatar Oct 17 '20 03:10 dragonpaw

Here is the algorithm I used to unflatten a dict https://stackoverflow.com/a/55545369/7391331

trallnag avatar Oct 31 '20 14:10 trallnag

If this is added, I think it would be good to also have a method to pack in into a flattened dict.

cdgriffith avatar Oct 31 '20 20:10 cdgriffith

Adding this feature in Box 7! Please test and give feedback if possible pip install python-box[all]~=7.0.0rc0

Specifically will require combo of default_box and box_dots, or which is same as using new DDBox class

cdgriffith avatar Jan 28 '23 20:01 cdgriffith

Added in 7.0.0

cdgriffith avatar Feb 04 '23 04:02 cdgriffith