How to print in new line after every 2 element

Question:

This is the json file:

{
    "x": [
        {
            "CourseCode" : "FHSC1014",
            "CourseName" : "MECHANICS"
        },
        {
            "CourseCode" : "FHCT1024",
            "CourseName" : "PROGRAMMING CONCEPT AND DESIGN"
        }
    ]
}

I want to print it like this;

FHSC1014    MECHANICS
FHCT1024    PROGRAMMING CONCEPT AND DESIGN

This is what I tried:

with open("test.json", 'r+') as f: 
    data = json.load(f)
    x = data['x']
    for i in x:
        for j in i:
            print(j)
Asked By: Cheah Ken Win

||

Answers:

you can get data like this:

with open("test.json", 'r') as f:
    data = json.load(f)
    x = data['x']
    for i in x:
        print(i['CourseCode'], i['CourseName'])
Answered By: xitas

You can do this by unpacking the values as follows:

import json

with open('test.json') as f:
  for d in json.load(f).get('x', []):
    print(*d.values())

Output:

FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
Answered By: DarkKnight
import json

with open("test.json", 'r') as f: 
    data = json.load(f)
    x = data['x']
    for i in x:
        print(i['CourseCode'], i['CourseName'])

The output

FHSC1014 MECHANICS
FHCT1024 PROGRAMMING CONCEPT AND DESIGN
Answered By: ma9

looping logic can be modified like the below:

for i in x:
 line=""       
 for j in i:
     if len(line)>0:
        line+="t"
     line+=i[j]
 print(line)
Answered By: v87
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.