[英]syntax error occured in combining json string in python
I have to create a json string with combined sub string.我必须创建一个带有组合子字符串的 json 字符串。 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
我是 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
.这会将
s
扩展为其键和值,以便它们直接成为master
的一部分。 Otherwise you have to specify keys and values directly with :
between.否则,您必须使用
:
between 直接指定键和值。
Note that this only works in Python 3.请注意,这只适用于 Python 3。
Try this one, it working in Python2:试试这个,它在 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这将适用于 python2 和 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这应该适用于 python 版本
master = {**s,'students':[s1,s2,s3]} master = {**s,'学生':[s1,s2,s3]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.