I have to create a json string with combined sub string. i coded as below
import json
s1 = {'name':'s1','age':15}
s2 = {'name':'s2','age':10}
s3 = {'name':'s3','age':12}
s = {'class':1}
master = {s,'students':[s1,s2,s3]}
print(master)
i got syntax error in line
master = {s,'students':[s1,s2,s3]}
I like to get out as follows
{'class':1,'students':[{'name':'s1','age':15},{'name':'s2','age':10},{'name':'s3','age':12}]}
Kindly help. I am newbie in python
Try:
master = {**s,'students':[s1,s2,s3]}
This will expand s
into its keys and values so that they are directly part of master
. Otherwise you have to specify keys and values directly with :
between.
Note that this only works in Python 3.
Try this one, it working in Python2:
import json
s1 = {'name':'s1','age':15}
s2 = {'name':'s2','age':10}
s3 = {'name':'s3','age':12}
s = {'class':1}
students = {'students':[s1,s2,s3]}
master = dict(s.items() + students.items())
print(master)
And this will working for python2 and python3
master = dict(list(s.items()) + list(students.items()))
One more way to achieve this
s1 = {'name':'s1','age':15}
s2 = {'name':'s2','age':10}
s3 = {'name':'s3','age':12}
s = {'class':1}
master = {}
master.update(s)
master.update({'students':[s1,s2,s3]})
This should work with both the python versions
master = {**s,'students':[s1,s2,s3]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.