如何在不重写现有词典的情况下将数据存储在Python词典中?你知道吗
例如:
output = {}
name = raw_input("Enter name")
age = input("Enter your age")
course = raw_input("Enter course")
school = raw_input("Enter school")
output['name'] = name
output['age'] = age
output['course'] = course
output['school'] = school
输出是这样的。你知道吗
{
"name": "Student 1",
"age": 25,
"course": "BSCS",
"school": "School 1"
}
然后,如果我添加另一个字段,它将覆盖现有数据。你知道吗
我怎样才能像这样存储它:
{
"students": [
{
"name": "Student1",
"age": 25,
"course": "BSIT",
"school": "School 1"
},
{
"name": "Student2",
"age": 26,
"course": "BSCS",
"school": "School 2"
},
{
"name": "Student3",
"age": 27,
"course": "BSCE",
"school": "School 3"
}
]
}
您还可以使用内置的
collections
模块和其中名为defaultdict
的类来解决它。你知道吗文件上说
Python Documentation
键是唯一的,因此如果要在一个键中存储多个值,请将该值设置为列表或其他dict、tuple、custom对象等。。你知道吗
例如
我会考虑创建一个类或使用元组将学生数据存储在列表中,但是,如果您想要类似JSON的格式,可以使用其他字典,如:
如果是一个物体,你会做出这样的东西:
所以现在你可以这样做:
相关问题 更多 >
编程相关推荐