0

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.

0

3 Answers 3

1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you experiment. It works and much helpful to understand more about Python.
1

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.

1 Comment

Thank you Christian. Your solution is easy and more understandable.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.