0

I have nested dictionary like following

{
    "A": 
        {"B": 
            {"C": 
                {"D": ['1','2','3']
                } 
        }
    },

    "AA": 
        {"BB": 
            {"CC": ['11', '22']} 
        }
}

I have to create a new dictionary in the following format:

{"xx-A-B-C-D": ['1','2','3'], "xx-AA-BB-CC": ['11','22']}

That is, the keys of the new dictionary are the original dictionary keys concatenated with 'xx' as the prefix, and the values are the values of the original dictionary.

I am still stuck after trying out for 5 hours. Any one care to peel the onion?

The following functions are my 2 attempts.

def get_value_from_dict(dict_obj, target):
    results = []
    def _get_value_from_dict(obj, results, target):
        if isinstance(obj, dict):
            for key, value in obj.items():
                if key == target:
                    results.append(value)
                elif isinstance(value, (list, dict)):
                    _get_value_from_dict(value, results, target)
        elif isinstance(obj, list):
            for item in obj:
                _get_value_from_dict(item, results, target)
        return results
    results = _get_value_from_dict(dict_obj, results, target)
    return results

def myprint(d):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v)
        else:
            print("{0} : {1}".format(k, v))
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
Austin
  • 55
  • 1
  • 8

1 Answers1

0

Use flatten_dict library:

Step 1: Install using pip install flatten-dict

Step 2:

2.1. Use the flatten function with the dictionary as an argument, and special_reducer to determine how to concatenate values.

d= {
    "A":
        {"B":
            {"C":
                {"D": ['1','2','3']
                }
        }
    },

    "AA":
        {"BB":
            {"CC": ['11', '22']}
        }
}

from flatten_dict import flatten

def special_reducer(k1, k2, seperator='-', prefix='xx'):
    if k1 is None:
        return prefix + seperator + k2
    else:
        return k1 + seperator + k2

r = flatten(d, reducer=special_reducer)

# {'xx-A-B-C-D': ['1', '2', '3'], 'xx-AA-BB-CC': ['11', '22']}
print(r)
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22
  • Thank you for your suggestion. I will try it out. following solves my issue - https://stackoverflow.com/questions/6027558/flatten-nested-dictionaries-compressing-keys – Austin Sep 01 '20 at 08:53
  • Welcome @Austin, using a library is more robust. Waiting to hear how it works for you – Aviv Yaniv Sep 01 '20 at 08:56