0

I want to be able to transform a dictionary in a list of options that can be set (with the full path), for example this should pass:

def test_dic_to_args(self):
    dic = {"x1": {"x2": "val1"}, "x2": "val3"}
    des = ["x1.x2:val1", "x2:val3"]
    self.assertEqual(conf.dict_to_args(dic), des)

Now I started to write it and I thought it was easy, but it's more tricky than I thought, with queues, type checking and so on.. Is there a smart way to solve this problem? Maybe the best option is still a recursive DFS, what do you think?

andrea_crotti
  • 3,004
  • 2
  • 28
  • 33

1 Answers1

6

If the dictionary is supposed to be arbitrarily nested, a recursive approach is most probably easiest.

def dict_to_args(d, prefix=()):
    for k, v in d.iteritems():
        if isinstance(v, dict):
            for x in dict_to_args(v, prefix + (k,)):
                yield x
        else:
            yield ".".join(prefix + (k,)) + ":" + v

Example:

>>> list(dict_to_args(dic))
['x2:val3', 'x1.x2:val1']
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841