Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.8K
Vistas
Python 3 - ValueError: no hay suficientes valores para desempaquetar (se esperaban 3, se obtuvieron 2)

Tengo un problema con mi programa Python 3. Uso Mac OS X. Este código se ejecuta correctamente.

 # -*- coding: utf-8 -*- #! python3 # sendDuesReminders.py - Sends emails based on payment status in spreadsheet. import openpyxl, smtplib, sys # Open the spreadsheet and get the latest dues status. wb = openpyxl.load_workbook('duesRecords.xlsx') sheet = wb.get_sheet_by_name('Sheet1') lastCol = sheet.max_column latestMonth = sheet.cell(row=1, column=lastCol).value # Check each member's payment status. unpaidMembers = {} for r in range(2, sheet.max_row + 1): payment = sheet.cell(row=r, column=lastCol).value if payment != 'zaplacone': name = sheet.cell(row=r, column=2).value lastname = sheet.cell(row=r, column=3).value email = sheet.cell(row=r, column=4).value unpaidMembers[name] = email # Log in to email account. smtpObj = smtplib.SMTP_SSL('smtp.gmail.com', 465) smtpObj.ehlo() smtpObj.login('abc@abc.com', '1234') # Send out reminder emails. for name, email in unpaidMembers.items() body = "Subject: %s - przypomnienie o platnosci raty za treningi GIT Parkour. " \ "\n\nPrzypominamy o uregulowaniu wplaty za uczestnictwo: %sw treningach GIT Parkour w ." \ "\n\nRecords show that you have not paid dues for %s. Please make " \ "this payment as soon as possible."%(latestMonth, name, latestMonth) print('Sending email to %s...' % email) sendmailStatus = smtpObj.sendmail('abc@abc.com', email, body) if sendmailStatus != {}: print('There was a problem sending email to %s: %s' % (email, sendmailStatus)) smtpObj.quit()enter code here

Los problemas comienzan cuando intento agregar el siguiente valor al ciclo for.

 # Send out reminder emails. for name, lastname, email in unpaidMembers.items() body = "Subject: %s - przypomnienie o platnosci raty za treningi GIT Parkour. " \ "\n\nPrzypominamy o uregulowaniu wplaty za uczestnictwo: %s %sw treningach GIT Parkour w ." \ "\n\nRecords show that you have not paid dues for %s. Please make " \ "this payment as soon as possible."%(latestMonth, name, lastname, latestMonth) print('Sending email to %s...' % email) sendmailStatus = smtpObj.sendmail('abc@abc.com', email, body)

La terminal muestra un error:

 Traceback (most recent call last): File "sendDuesEmailReminder.py", line 44, in <module> for name, email, lastname in unpaidMembers.items(): ValueError: not enough values to unpack (expected 3, got 2)
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Probablemente quieras asignar el lastname que estás leyendo aquí

 lastname = sheet.cell(row=r, column=3).value

a algo; actualmente el programa simplemente lo olvida

podrías hacer eso dos líneas después, así

 unpaidMembers[name] = lastname, email

su programa seguirá fallando en el mismo lugar, porque .items() todavía no le dará 3 tuplas, sino algo que tiene esta estructura: (name, (lastname, email))

la buena noticia es que python puede manejar esto

 for name, (lastname, email) in unpaidMembers.items():

etc.

over 4 years ago · Santiago Trujillo Denunciar

0

1. Primero debe entender el significado del error

Error not enough values to unpack (expected 3, got 2) significa:

una tupla de 2 partes , pero asignada a 3 valores

y he escrito un código de demostración para mostrártelo:

 #!/usr/bin/python # -*- coding: utf-8 -*- # Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)' # Author: Crifan Li # Update: 20191212 def notEnoughUnpack(): """Showing how to understand python error `not enough values to unpack (expected 3, got 2)`""" # a dict, which single key's value is two part tuple valueIsTwoPartTupleDict = { "name1": ("lastname1", "email1"), "name2": ("lastname2", "email2"), } # Test case 1: got value from key gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail)) # gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2) # Test case 2: got from dict.items() for eachKey, eachValues in valueIsTwoPartTupleDict.items(): print("eachKey=%s, eachValues=%s" % (eachKey, eachValues)) # same as following: # Background knowledge: each of dict.items() return (key, values) # here above eachValues is a tuple of two parts for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items(): print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2)) # but following: for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2) pass if __name__ == "__main__": notEnoughUnpack()

usando el efecto de depuración de VSCode :

notEnoughDesempaquetar CrifanLi

2. Por tu código

 for name, email, lastname in unpaidMembers.items():

pero error ValueError: not enough values to unpack (expected 3, got 2)

significa que cada elemento (un valor de tupla) en miembros no unpaidMembers , solo tiene 1 parte: email , cuyo código correspondiente anterior

 unpaidMembers[name] = email

entonces debería cambiar el código a:

 for name, email in unpaidMembers.items():

para evitar errores.

Pero, obviamente, espera un lastname adicional, por lo que debe cambiar su código anterior a

 unpaidMembers[name] = (email, lastname)

y mejor cambio a mejor sintaxis:

 for name, (email, lastname) in unpaidMembers.items():

entonces todo está bien y claro.

over 4 years ago · Santiago Trujillo Denunciar

0

En esta línea:

 for name, email, lastname in unpaidMembers.items():

unpaidMembers.items() debe tener solo dos valores por iteración.

Aquí hay un pequeño ejemplo para ilustrar el problema:

Esto funcionará:

 for alpha, beta, delta in [("first", "second", "third")]: print("alpha:", alpha, "beta:", beta, "delta:", delta)

Esto fallará, y es lo que hace su código:

 for alpha, beta, delta in [("first", "second")]: print("alpha:", alpha, "beta:", beta, "delta:", delta)

En este último ejemplo, ¿qué valor en la lista se asigna a delta ? Nada, no hay suficientes valores, y ese es el problema.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda