title: Python to unpack key value pairs from various layers of a dict, list, dict structure into separate JSON arrays nested within JSON object
body: <p>Scenario:</p>
  <p>I need to extract keys and values from a list of python dictionary structures (constructed in previous steps) into respective 'fields' and 'values' JSON arrays nested in JSON object(s).</p>
  <p>This is part of a complex JSON string I am producing where I have multiple for loop iterators nested within iterators but this key value pair is the center of of lollipop and the part I am stuck on and I have no idea how to break out the keys and values into respective arrays. Below is the portion I was able to get returned but this is just returning the individual dict structures in a single 'fields' array:</p>
  <pre><code>&quot;table&quot;: &quot;name&quot;, 
  &quot;inserts&quot;: [
      {
          &quot;fields&quot;: [
              {
                  &quot;id&quot;: 1,
                  &quot;name&quot;: &quot;National Monument&quot;
              }
          ]
      }
  ]
  </code></pre>
  <p>I am ham-fisting around with several approaches to try and break this out and below is just one of many failed attempts:</p>
  <pre><code>nameList = [ {'id': 1, 'name': 'National Monument'}, {'id': 1, 'name': &quot;Joe's Bar&quot;} ]
  
  result = []
  i = 0
  for d in nameList:
      for k, v in d.items():
          result[i][&quot;inserts&quot;].append({&quot;fields&quot;:k})
          result[i][&quot;inserts&quot;].append({&quot;values&quot;:v})
      i += 1
  
  pprint(result)
  </code></pre>
  <h1>produces error 'IndexError: list index out of range'</h1>
  <p>This is what I need returned (please disregard any non valid JSON and focus on just the distillation of key value pairs into separate JSON arrays).</p>
  <pre><code>&quot;table&quot;: &quot;name&quot;,
  &quot;inserts&quot;: [
      {
          &quot;fields&quot;: [
              &quot;id&quot;,
              &quot;name&quot;
          ],
          &quot;values&quot;: [
              1,
              &quot;National Monument&quot;
          ]
      }
  ]
  </code></pre>