From ff0166c896f0c8379b47492b7e8ce3bdf5aa2b87 Mon Sep 17 00:00:00 2001 From: Alex Telon Date: Fri, 25 Oct 2019 17:32:21 +0200 Subject: [PATCH] Unflatten for by benbowen unflatten does not support lists, the github user benbowen created an issue: https://github.com/ianlini/flatten-dict/issues/8 and described a solution that worked for him. --- src/flatten_dict/flatten_dict.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/flatten_dict/flatten_dict.py b/src/flatten_dict/flatten_dict.py index 9e46e78..8bd92bf 100644 --- a/src/flatten_dict/flatten_dict.py +++ b/src/flatten_dict/flatten_dict.py @@ -101,11 +101,25 @@ def nested_set_dict(d, keys, value): assert keys key = keys[0] if len(keys) == 1: - if key in d: - raise ValueError("duplicated key '{}'".format(key)) - d[key] = value + if type(d) == list: + d.append(value) + else: + d[key] = value return - d = d.setdefault(key, {}) + + # the type is a string so make a dict if none exists + if type(keys[1]) == int: + if key in d: + pass + else: + d[key] = [] + d = d[key] + elif type(key)==int: + if (key+1) > len(d): + d.append({}) + d = d[key] + else: + d = d.setdefault(key, {}) nested_set_dict(d, keys[1:], value)