pythonmysqliterable-unpacking

How to automatically unpack list that contains some 0 values?


When I try to unpack a list data for a MySQL database query that has some columns with value 0, I get an error.

Name (varchar) Apples(int) Candies(int) Color (varchar)
John 5 0 Blue

If I unpack my query result like:

name, apples, candies, color = mylist

I'll get a NoneType error because candies values (in this example) is considered as None rather than 0.

The workaround I currently have is (which defeats the purpose and benefit of unpacking):

name = mylist[0]
if apples is None:
    apples = 0
else apples = mylist[1]
if candies is None:
    candies = 0
else candies = mylist[2]
color = mylist[3]

So my question is, is there anyway I can unpack mylist when one (or more) items have a value of 0 (and not null or None) without going through each one of them as "if x is None: x = 0"?


Solution

  • You can still using unpacking, just fix up the None values afterward.

    name, apples, candies, color = mylist
    if apples is None:
        apples = 0
    if candies is None:
        candies = 0
    

    If you have lots of columns to fix, you can use a list comprehension to fix up all the None values in the list.

    mylist = [0 if x is None else x for x in mylist]
    name, apples, candies, color = mylist
    

    I doubt that 0 is really being turned into None, you probably have NULL values in the table. You can use IFNULL() to convert them:

    SELECT name, IFNULL(apples, 0), IFNULL(candies, 0), color
    FROM tablename