Converting python dictionary to unique key-value pairs
<p>I want to convert a python dictionary to a list which contains all possible key-value pair. For example, if the dict is like:</p>

<pre><code>{
    "x": {
            "a1": { "b": {
                            "c1": { "d": { "e1": {}, "e2": {} } },
                            "c2": { "d": { "e3": {}, "e4": {} } }
                        }
                },
            "a2": { "b": {
                            "c3": { "d": { "e1": {}, "e5": {} } },
                            "c4": { "d": { "e6": {} } }
                        }
                 }
       }
}
</code></pre>

<p>I would like to get a list like:</p>

<pre><code>[
  { "x": "a1", "b": "c1", "d": "e1" },
  { "x": "a1", "b": "c1", "d": "e2" },
  { "x": "a1", "b": "c2", "d": "e3" },
  { "x": "a1", "b": "c2", "d": "e4" },
  { "x": "a2", "b": "c3", "d": "e1" },
  { "x": "a2", "b": "c3", "d": "e5" },
  { "x": "a2", "b": "c4", "d": "e6" }
]
</code></pre>

<p>I am struggling to write a recursive function.
I have written this, but it is not working</p>

<pre><code>def get_list(groups, partial_row):
    row = []
    for k, v in groups.items():
        if isinstance(v, dict):
            for k2, v2 in v.items():
                partial_row.update({k: k2})
                if isinstance(v2, dict):
                    row.extend(get_list(v2, partial_row))
                else:
                    row.append(partial_row)

    return row
</code></pre>

<p>You are missing one condition check in the following section in your original solution:</p>

<pre><code>if isinstance(v2, dict):
    row.extend(get_list(v2, partial_row))
else:
    row.append(partial_row)
</code></pre>

<p>Rather it has to be</p>

<pre><code>if isinstance(v2, dict) and v2:
    row.extend(get_list(v2, partial_row))
else:
    row.append(partial_row)
</code></pre>

<p>Due to the missing <code>and v2</code>, the <code>else</code> block never gets executed and you are always getting the empty list as a result.</p>

python list dictionary flatten