Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fetch key names of dictionary into list | python |

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading