如何在不重写字典的情况下将数据存储在字典中?

2024-09-28 22:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在不重写现有词典的情况下将数据存储在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"
        }
    ]
}

Tags: 数据nameinputoutputageyourraw情况
2条回答

您还可以使用内置的collections模块和其中名为defaultdict的类来解决它。你知道吗

import collections as cl
output = cl.defaultdict(list)
for i in range(n):
    name, age, course, school = map(str, raw_input().split())
    age, key, value = int(age), "student" + str(i + 1), dict()
    value["name"], value["age"], value["course"], value["school"] = name, age, course, school
    output[key] = value

文件上说

This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

Python Documentation

键是唯一的,因此如果要在一个键中存储多个值,请将该值设置为列表或其他dict、tuple、custom对象等。。你知道吗

例如

my_dict = {}
my_dict["students"] = []
my_dict["students"].append( new_dict )

我会考虑创建一个类或使用元组将学生数据存储在列表中,但是,如果您想要类似JSON的格式,可以使用其他字典,如:

new_dict = {"name": "Max", "age":12}
my_dict["students"].append( new_dict )

如果是一个物体,你会做出这样的东西:

class Student(object):

    __init__(self, name, age):
        self.name = name
        self.age = age

所以现在你可以这样做:

my_dict.append( Student("max", 12) )

相关问题 更多 >