Error with append and creating dictionary in append. ValueError: not enough values to unpack (expected 3, got 2)

Question:

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()
Asked By: Al3jandr0

||

Answers:

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():
        for name,num in val:
            print( f"{key}, {name} {num}" )

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) )
Answered By: Tim Roberts

You need nested loops to loop over the residents of each city.

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

    for city, name1, name2, number in data.fetchall():   
        x.setdefault(city, []).append([name1, number])

    for key_city, residents in x.items():
        avg_number = sum(res[1] for res in residents) / len(residents)
        print(f'City: {key_city}nAvg: {avg_number}')
        for res_name, res_number in residents:
            print(f' Name: {res_name}, Age: {res_number}')
Answered By: Barmar