Home > Software engineering >  fetch key names of dictionary into list | python |
fetch key names of dictionary into list | python |

Time:03-24

I have a json data as shown below

json data

data = '''
{
 "p1":[ {"Name":"A","Age":45} , 
             {"Name":"B","Age":26} ],
 "p2":[ {"Name":"C","Age":25} , 
             {"Name":"D","Age":26} ]
}
'''

My code :

import json

jdata = json.loads(data)
jkey  = jdata.keys()   # (['p1','p2']) 
jheader = []
for row in jkey:
    jheader.append(jdata[row][0])
    break;

How to get only headers into header list

Expected output :

header = ['Name','Age']

CodePudding user response:

This creates a list of dicts, and a list with the keys. Is that what you're after?

import json

jdata = json.loads(data)
jheader = []
jrows = []
for key,parts in jdata.items():
    if not jheader:
        jheader = list(parts[0].keys())
    jrows.extend(parts)
  • Related