0

I am referring this question

This is my code

my_dictionary={}
a=[]
for i in range(1,5)

    jsonstring = {id[i] : marks[i]}
    a.append(jsonstring)
my_dictionary=json.dumps(a)
print(my_dictionary)

This is the output

[{"123": [86, 0, 0, 96, 45.5]}]

I want the string such as

{"123": [86, 0, 0, 96, 45.5],"124": [89, 0, 90, 96, 87],....}
5
  • 1
    The whole JSON encoding-decoding is a red herring. It achieves nothing. It is busy-work for no gain. Why do it at all? Just append jsonstring (which is not a string but a dictionary) to your list. Commented Mar 12, 2016 at 15:09
  • is there any better way? Commented Mar 12, 2016 at 15:09
  • 1
    Yes, just append the dictionary to your list, and encode the list. Commented Mar 12, 2016 at 15:10
  • At least, I'm assuming you want studentInfo to be a list. Did you mean for it to be one big dictionary instead? Commented Mar 12, 2016 at 15:14
  • Can you please update your question with some sample input, and expected output? That'd avoid further speculation. Commented Mar 12, 2016 at 15:30

1 Answer 1

2

Just encode the end result. You are building a Python dictionary, add all your keys to one dictionary and encode the final result. Encoding to JSON then decoding again doesn't really achieve anything here.

studentInfo = {}
for i in range(1,5)
    studentInfo[id[i]] = marks[i]

jsonstring = json.dumps(studentInfo)

Rather than use an index, you can use zip() to combine id entries with marks entries:

studentInfo = {}
for student_id, student_marks in zip(id, marks):
    studentInfo[student_id] = student_marks

jsonstring = json.dumps(studentInfo)

Better still, you can simply produce the whole dictionary from the zip() output directly:

studentInfo = dict(zip(id, marks))
jsonstring = json.dumps(studentInfo)
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, Sorry but append is not working its just overwriting the value is there any problem?
@BhavikJoshi: not working doesn't tell me anything. Overwriting what? list.append() just adds the result to the end of a list, so nothing will be overwritten. Please add sample input and expected output to your question, and we can then work to produce that output.
so the string is there but it has only one previously appended string not the whole list of string added.
@BhavikJoshi: Your updated question shows you want one dictionary with multiple keys. Updated my answer to show that. I'm still not clear as to what you mean by a whole list here.

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.