Skip to content Skip to sidebar Skip to footer

Flatten Nested Dict From Pandas Dataframe

I have a for loop that is looping over a list for completing an API call. With each loop I have the json response run through pandas and append to REPL_ID: import requests import j

Solution 1:

It's hard to implement directly in your code but you can just take an extra step with your output. Simply loop over your dic of dics {{},{},...}, take each dic and add each entry (key/values) to a new dic leading to one unnested dic.

original_output = [{
  1: {'NodeId': 'node01@00-68D6FB-65377D-4804B8-A7F390[1-1-2D]',
      'ID': '006bdade-49a8-4875-93de-54ba356403c4'},
  2: {'NodeId': 'node01@00-68D6FB-65377D-4804B8-A7F390[1-1-2D]',
      'ID': 'f8613a7d-30b1-4407-82f0-b92c82c6c422'}
  }, {
  5: {'NodeId': 'node03@00-94CF47-90E188-48728F-0538D8[1-1-19]',
      'ID': '065999f6-a3fe-4b1d-af35-7556efcc530e'},
  6: {'NodeId': 'node03@00-94CF47-90E188-48728F-0538D8[1-1-19]',
      'ID': 'cf96419c-a188-4b1a-85d6-bde41dbbe3ef'}
}]


new_dict = {}
c = 0 
for dic in original_output:
    for key in dic.keys():
        new_dict[c] = dic[key]
        c += 1
new_dict

Out:
{0: {'NodeId': 'node01@00-68D6FB-65377D-4804B8-A7F390[1-1-2D]',
  'ID': '006bdade-49a8-4875-93de-54ba356403c4'},
 1: {'NodeId': 'node01@00-68D6FB-65377D-4804B8-A7F390[1-1-2D]',
  'ID': 'f8613a7d-30b1-4407-82f0-b92c82c6c422'},
 2: {'NodeId': 'node03@00-94CF47-90E188-48728F-0538D8[1-1-19]',
  'ID': '065999f6-a3fe-4b1d-af35-7556efcc530e'},
 3: {'NodeId': 'node03@00-94CF47-90E188-48728F-0538D8[1-1-19]',
  'ID': 'cf96419c-a188-4b1a-85d6-bde41dbbe3ef'}}

EDIT: added the 'reindexing' via the c variable

Post a Comment for "Flatten Nested Dict From Pandas Dataframe"