Smith Dwayne
Smith Dwayne

Reputation: 2807

Writing json from two lists in Python

I am new to Python. I have two lists. One is key list and another list is value list.

title = ["Code","Title","Value",....] value = [["100","abcd",100",...],["101","efgh",200",...],...] data={} data.setdefault("data",[]).append({"code": sp[0],"val": sp[2]})

this code gives me the following result.

{'data': [{'code': '100', 'val': '100'},{'code': '101', 'val': '200'}]}

But I want the result as the below,

{ "100": { "Title": "abcd", "Value": "100", ............, ............}, "101": { "Title": "efgh", "Value": "200", ............, ............} }

i.e., The first column of the value list should be the key of every Json array list and other items of the lists should be generated as key and value pair. How can I generate the Json array using Python code referring that two lists.

Upvotes: 0

Views: 714

Answers (3)

Christian
Christian

Reputation: 76

You can build a dict with this lists. I made a quick snippet just for you to understand

title = ["Code","Title","Value"]
value = [['100','abcd','100'],['101','efgh','200']]
data={}

for whatever in value:
    your_titles = {}
    print(whatever[0])
    your_titles[title[1]] = whatever[1]
    your_titles[title[2]] = whatever[0]
    your_titles[title[0]] = whatever[2]
    data[whatever[0]] = your_titles
print(data)

The output: {'100': {'Code': '100', 'Value': '100', 'Title': 'abcd'}, '101': {'Code': '200', 'Value': '101', 'Title': 'efgh'}}

Please read this tutorial and try to make it yourself. This is not the optimal solution for this problem.

Upvotes: 1

experiment
experiment

Reputation: 315

As it is not mentioned that about the size of list ,the below could would do the job.I am using python3.x

title = ["Code","Title","Value"]
value = [["100","abcd","100"],["101","efgh","200"]]
dic1={}
for i in range(len(title)-1):
    for j in range(len(title)-1):
        dic1.setdefault(value[i][0],{}).update({title[j+1]:value[i][j+1]})

Output is

{'101': {'Title': 'efgh', 'Value': '200'}, '100': {'Title': 'abcd', 'Value': '100'}}

I hope it is helpful!

Upvotes: 1

Upasana Mittal
Upasana Mittal

Reputation: 2680

Make a data frame and then set the column to index and then convert it to json:

    data_frame = pd.DataFrame(columns = title, data = value)
    data = data_frame.set_index('Code')

    json1 = data.to_json(orient='index')

Upvotes: 0

Related Questions