gmr / flatdict

Python module for interacting with nested dicts as a single level dict with delimited keys.
https://flatdict.readthedocs.io
BSD 3-Clause "New" or "Revised" License
112 stars 32 forks source link

`FlatterDict`: Unflattening list values from a plain old dict does not work #49

Open whophil opened 2 years ago

whophil commented 2 years ago

Unflattening a FlatterDict with list values works fine if that FlatterDict object was created from a dict with list values. However, if that dict is converted to a plain old dict containing delimited keys, the keys which represent lists do not property unflatten - instead, it unflattens to a dict whose keys are the string integers.

As an example:

import flatdict
import json

orig = {
    'list': [0, 1, 2]
}

# flatten the dict
print('-' * 40 + '\nFlattened 2\n' + '-' * 40)
flat = flatdict.FlatterDict(orig)
print(json.dumps(dict(flat), indent=2))

# unflatten from the `flat` object directly
print('-' * 40 + '\nUnflattened 1\n' + '-' * 40)
unflat_1 = flat.as_dict()
print(json.dumps(unflat_1, indent=2))

# unflatten from a dict of `flat`
print('-' * 40 + '\nUnflattened 2\n' + '-' * 40)
flat_2 = flatdict.FlatterDict(dict(flat))
unflat_2 = flat_2.as_dict()
print(json.dumps(unflat_2, indent=2))

Produces:

----------------------------------------
Flattened 2
----------------------------------------
{
  "list:0": 0,
  "list:1": 1,
  "list:2": 2
}
----------------------------------------
Unflattened 1
----------------------------------------
{
  "list": [
    0,
    1,
    2
  ]
}
----------------------------------------
Unflattened 2
----------------------------------------
{
  "list": {
    "0": 0,
    "1": 1,
    "2": 2
  }
}

This is so because FlatterDict carries around an original_type, which stores information about the key types, and this information is lost when you go to a regular dictionary.