I am trying to create a list with multiple dicts like this [ { token_id: 7183938r8393}, { token_id: 82838rhf88381}, ]
this is what I have now
import pyodbc
from sqlalchemy import create_engine
import pandas as pd
import json
def all_token(x):
con = pyodbc.connect(Trusted_connection='yes', driver= '{SQL Server}',server = 'DESKTOP-
9S6405A\SQLEXPRESS' ,database ='Q42')
cursor = con.cursor()
list = []
my_dict = {}
cursor.execute("SELECT [tokens ].token_id FROM [tokens ]")
for row in cursor.fetchall():
list.append(row)
print(list)
def listToDict(list):
convert = { f"Token ID {str(i)}" : list[i][0] for i in range(0, len(list))}
return convert
all_token(list)
print(list)
dict = listToDict(list)
print(dict)
this is the error message
TypeError: object of type 'type' has no len()
CodePudding user response:
list = []
In this line you have defined a variable called list
.
This will mess everything up because list
is a class.
Do not use keywords as variable names
Instead, rename the variable to something like my_list
CodePudding user response:
TypeError: object of type 'type' has no len()
The error here is that list
is a reserved word and isn't supposed to be used as a variable. Change your variable name and you're good to go!
CodePudding user response:
Your indentation seems to be broken. Also, you shouldn't name list with a name of a keyword. So I will use list1
.
You send list1
to the all_token()
which does not make any sense, because you will create list1
in all_token
function. So may be you should type:
return list1
instead of:
print(list1)
...and then instead of
all_token(list1)
write...
list1 = all_token()
Also, you need to remove x
in arguments to all_token(). Now you have list1
and can convert it to a dictionary or whatever you want.