Home > other >  Error with append and creating dictionary in append. ValueError: not enough values to unpack (expect
Error with append and creating dictionary in append. ValueError: not enough values to unpack (expect

Time:12-13

I would like to add the city to it and then print ouput: Liverpool, Jonny 33. I would like to set city as primary key.

Before adding city, my code worked fine because i used name as primary key, and i got output: Jonny 33 , under it Tiffany 45, under it Margot 21. But now, adding the city key, i have this error:

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

Maybe the mistake is that i created the dictionary wrong and messed up the way i added city to it, and so it's not being called correctly in the second loop.

How can I also add city (before the name)?

import sqlite3
c = sqlite3.connect('abc')
cursor = c.cursor()

x = {}

def Button_func():
   data = c.execute('SELECT city, name1, name2, number FROM MyListTable')

    for r in data.fetchall():   
        if r[0] not in x:
            x[r[0]] = []
        x[r[0]].append([r[1], r[3]])

    for key_city, val_name, val_number in x.items():
        result = sum(val_number) / 2
        print(key_city, val_name, result)


Button_func()

CodePudding user response:

This will print all the names in the format you want:

import sqlite3
c = sqlite3.connect('abc')
cursor = c.cursor()

rows = {}

def Button_func():
    data = c.execute('SELECT city, name1, name2, number FROM MyListTable')
    for city,name1,name2,number in data.fetchall():   
        if city not in x:
            x[city] = []
        x[city].append( (name1,number) )

    for key,val in x.items():
        print( f"{key}, {val[0]} {val[1]}" )

Button_func()

Your code implies that you are supposed to print the average age of the people from each city. In that case, you wouldn't want the people's names in there.

    for key,val in x.items():
        print( key, sum(k[0] for k in val)//len(val) )

CodePudding user response:

items() returns a sequence of (key, value) tuples. If you want to unpack the values into variables, you need to use a nested tuple:

for key_city, (val_name, val_number) in x.items():
  • Related