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],....}
Community
  • 1
  • 1
Bhavik Joshi
  • 2,557
  • 6
  • 24
  • 48

1 Answers1

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Hi, Sorry but append is not working its just overwriting the value is there any problem? – Bhavik Joshi Mar 12 '16 at 15:26
  • @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. – Martijn Pieters Mar 12 '16 at 15:31
  • so the string is there but it has only one previously appended string not the whole list of string added. – Bhavik Joshi Mar 12 '16 at 15:37
  • @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. – Martijn Pieters Mar 12 '16 at 17:43