I have 3 lists:
filtered_headings = [‘Educational Institutions’, ‘Number of students’, ‘Number of teaching staffs’, ‘Number of non- teaching staffs’]
sub_headings = [‘College/University’, ‘Basic Level’, ‘Secondary Level’, ‘Secondary Level’, ‘College/University’, ‘Basic Level’, ‘Secondary Level’, ‘College/University’, ‘Basic Level’, ‘Basic Level’, ‘College/University’, ‘Secondary Level’]
values = [‘2′, ’10’, ’12’, ‘566’, ‘400’, ‘799’, ‘355’, ‘115’, ’12’, ‘115’, ’11’, ’11’]
I want them converted into JSON in this format:
{
"Educational Institutions": {
"College/University": "2",
"Basic Level": "10",
"Secondary Level": "12"
},
"Number of students": {
"Secondary Level": "566",
"College/University": "400",
"Basic level": "799"
},
"Number of teaching staffs": {
"Secondary Level": "355",
"College/University": "115",
"Basic Level": "12"
},
"Number of non- teaching staffs": {
"Basic Level": "115",
"College/University": "11",
"Secondary Level": "11"
}
}
I get the following output:
{
"Educational Institutions": {
"College/University": "11",
"Basic Level": "115",
"Secondary Level": "11"
},
"Number of students": {
"College/University": "11",
"Basic Level": "115",
"Secondary Level": "11"
},
"Number of teaching staffs": {
"College/University": "11",
"Basic Level": "115",
"Secondary Level": "11"
},
"Number of non- teaching staffs": {
"College/University": "11",
"Basic Level": "115",
"Secondary Level": "11"
}
}
It is repeating the last 3 values over and over again, how do i get the output in intend format?
My code is:
result = {}
for indv_heading in filtered_headings:
data_dict = {sub_heading: value for sub_heading,
value in zip(sub_headings, values)}
result[indv_heading] = data_dict
# print(result)
json_data = json.dumps(result, indent=1)
print(json_data)
2
Answers
You can zip
sub_headings
andvalues
into pairs and useitertools.batched
to chunk them into groups of 3 to construct sub-dicts, and then zipsub_headings
with the sub-dicts to produce a key-value sequence for the main dict:itertools.batched
was introduced in Python 3.12. If you’re using an earlier Python version, you can use thebatched
recipe instead.I’m not sure if the length of the lists will grow in the future, if not, we can get a solution not suitable for production but yes to be easy, readable and understandable.
Easy not optimized solution:
Also, is it possible for you to tell us where are you getting your data from?
Because maybe there’s a more efficient way to do it.