【问题标题】:how do i fix this function with dictionary to add and print added people?如何使用字典修复此功能以添加和打印添加的人?
【发布时间】:2018-05-09 16:27:24
【问题描述】:

目前我试图解决我编写的代码中的一个问题,由于某种原因,每当我调用 imprimir() 时,它只显示最后添加的人,而它应该显示所有添加的人。

libro = {}


def agregar(rut, nombre, edad):

    estudiante = {}

    estudiante['rut'] = rut
    estudiante['nombre'] = nombre
    estudiante['edad'] = edad

    libro['rut'] = estudiante


def imprimir():
    for rut in libro:
        estudiante = libro[rut]
        print(estudiante['rut'], estudiante['nombre'], estudiante['edad'])


def main():
    contador = 0
    while contador < 2:
        rut = input("rut: ")
        nombre = input("nombre: ")
        edad = input("Edad: ")
        contador = contador + 1
        agregar(rut, nombre, edad)
    imprimir()

main()

我将代码限制为只能添加 2 人。因此,如果我写的第一个人,rut = 1,nombre = 1 和 edad = 1,而对于第二个人,rut = 2,nombre = 2 和 edad = 2。使用 main() 时,它应该打印: 1 1 1 2 2 2 但它只是打印 2 2 2 而 1 1 1 not found,我的猜测是添加的人没有被添加,而是被重写,但我找不到原因,如果我在 main() 的 while 中包含 imprimir()一旦我完成添加一个人,它就会打印每个人,但它的想法是,一旦我完成添加他们,程序应该打印所有添加的人。

【问题讨论】:

    标签: python python-3.x function dictionary


    【解决方案1】:

    问题是您使用相同的键添加项目,因此dict 只是用您添加的每个条目覆盖最后一个值...

    libro = {}
    
    
    def agregar(rut, nombre, edad):
    
        estudiante = {}
    
        estudiante['rut'] = rut
        estudiante['nombre'] = nombre
        estudiante['edad'] = edad
    
        # this would override the previous entry since it's always the same key
        libro['rut'] = estudiante
        # use a key that is unique and all entries will be preserved
        libro[rut] = estudiante
        # or for some truly unique keys
        libro[str(uuid.uuid4())] = estudiante
    

    【讨论】:

    • Bug 在这一行 libro['rut'] = estudiante 更改为 libro[rut] = estudiante
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多