Converting PYODBC output into an int
Pulling data from a SQL query that gives me 1 number that is stored in a PYODBC row. I want to then add that number to another variable in the file. Pseudocode below -
prev = 5
cursor.execute("select statement")
pulledNumber = cursor.fetchall()
value = [row[2] for row in pulledNumber]
final = prev + value
Getting a type error (list and int operation). Tried to cast the list to an int a few different ways but could not get it to work
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Nested list in C# with layers
I am not an expert coder and I have just started learning about Generic data types. What I am trying to code is a List inside of a list inside of a list .
For example- at the first level - I want numbers each inside of a list
Layer 1 list1=[1,2,3,4,5,6,7,8,9,10......1000] ,
At the 2nd layer I'd like list from 1st layer added as an element to a parent list 2 when layer 1 meets certain condition- ex layer 1 reaches max=10
List2=[List1[0:10],List1[10:20],List1[20:30], .....] ,
At layer 3, i'd like to repeat the process, all elements of layer 2 get added as an element to a new parent list 3 when layer 2 meets a max condition. list3[0]=[list2[0:10],list2[10:20],list2[20:30]..... and so on.
Only the first layer would have integer values, the successive layer would be a wrapping of it's the previous layer. How can I code this in C#?
Thanks!
-
python list ofwords.the program outputsthosewords&theirfrequencies.Ex:if the input is:hey hi Mark hi mark the output is: hey 1 hi 2 Mark 2 hi 2 mark 2
I thought I could use this code:
wordInput = input() myList = wordInput.split(" ") for i in myList: print(i,myList.count(i))
but its output is:
hey 1 Hi 1 Mark 1 hi 1 mark 1
How can I make it:
Hey 1 Hi 2 Mark 2 hi 2 mark 2
-
How to convert DataTable to List<T> in C#
For convert DataTable to List you can used the AutoMapper Library and you can do it automatically
-
using cast to convert text to date and min function together
select location, min(cast(date as date)) as Date, new_cases from corona group by location
I wanted to convert datatype of date column to date datatype. Then I wanted to find the minimum by grouping location(countries). But the Date column is given me all null values. The dataset im using is corona from "ourworldindata". Any help will be appreciated. Thank you in advance.
-
Why casting a very large long number to int gives us a strange output (Java)?
I was practicing some castings in Java and I faced a situation for which I couldn't find any answers, anywhere. There are a lot of similar questions with answers, but none gave me an explanation for this particular case.
When I do something like
long l = 165787121844687L; int i = (int) l; System.out.println("long: " + l); System.out.println("after casting to int: " + i);
The output is
long: 165787121844687 after casting to int: 1384219087
This result is very intriguing for me.
I know that the type long is a 64-bit integer, and the type int is a 32-bit integer. I also know that when we cast a larger type to a smaller one, we can lose information. And I know that there is a Math.toIntExact() method that is quite useful.
But what's the explanation for this "1384219087" output? There was loss of data, but why this number? How "165787121844687" became "1384219087"? Why does the code even compile?
That's it. Thanks!
-
TypeError: list indices must be integers
I'm trying to insert an item from one list to another and using an item from a list of numbers for the index but I'm getting this error even though I'm using integers for index numbers
and the other thing is that the same item is accepted as an index in the line just before the error
I even tried putting a number there just to test it but it gave me the same error
here's the code:
FoundLetters = ['p', 'l', '-', 'i', 'n'] MissingLetters = [] AllLetters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] def MissingCount(): for j in range(len(FoundLetters)): if FoundLetters[j] == '-': MissingLetters.append(int(j)) def iterate(): for i in range(len(AllLetters)): for i in AllLetters: FoundLetters.pop(MissingLetters[0]) FoundLetters.insert(MissingLetters[0], AllLetters[i]) MissingCount() iterate()
and this was the exact error:
Traceback (most recent call last): File "main.py", line 26, in <module> iterate() File "main.py", line 22, in iterate FoundLetters.insert(MissingLetters[0], AllLetters[i]) TypeError: list indices must be integers or slices, not str ** Process exited - Return Code: 1 ** Press Enter to exit terminal
-
Getting Error with UI for TikTok algorithm
So I basically made a algorithm which takes the users input and decided on a rank from 1-100 and puts it on a UI.
import tkinter, os, webbrowser, random #algorithm def tiktok_algorithm(share_count, like_count, comment_count, posts): if (share_count >= 10000 and like_count >= 5000 and posts >20 and comment_count.find("amazing")!= -1): rank = 1 elif (share_count >= 7000 and like_count >= 2000 and posts >25 and comment_count.find("amazing")!= -1): rank = random.randint(2,10) elif (share_count >= 6000 and like_count >= 1500 and posts >25 and comment_count.find("amazing")!= -1): rank = random.randint(11,20) elif (share_count >= 5000 and like_count >= 1300 and posts >20 and comment_count.find("amazing")!= -1): rank = random.randint(21,40) elif (share_count >= 4000 and like_count >= 1000 and posts >15 and comment_count.find("nice")!= -1): rank = random.randint(41,55) elif (share_count >= 3000 and like_count >= 500 and posts >11 and comment_count.find("cool")!= -1): rank = random.randint(56,70) elif (share_count >= 2000 and like_count >= 300 and posts >11 and comment_count.find("ok")!= -1): rank = random.randint(71,80) elif (share_count >= 1000 and like_count >= 150 and posts >11 and comment_count.find("ok")!= -1): rank = random.randint(81,90) elif (share_count >= 400 and like_count >= 100 and posts >11 and comment_count.find("ok")!= -1): rank = random.randint(91,97) else: rank = random.randint(98,100) return(rank) def calculate_ranking(): # read in the entry values like_count = int(likes_entry.get()) comment_count = comment_entry.get() posts = int(posts_entry.get()) shares = int(share_entry.get()) rank = tiktok_algorithm(like_count, comment_count, shares, posts) # "print" result to result label result_label.config(text="Your tiktok ranking is: " + str(rank)) root = tkinter.Tk() root.title("Magic Tiktok Algorithm") root.geometry("400x600") # likes likes_label = tkinter.Label(root, text="Number of Likes:") likes_label.pack() likes_entry = tkinter.Entry(root) likes_entry.pack() # comment comment_label = tkinter.Label(root, text="Comment:") comment_label.pack() comment_entry = tkinter.Entry(root) comment_entry.pack() #shares share_label = tkinter.Label(root, text="number of shares:") share_label.pack() share_entry = tkinter.Entry(root) share_entry.pack() #posts posts_label = tkinter.Label(root, text="Posts") posts_label.pack() posts_entry = tkinter.Entry(root) posts_entry.pack() #image img_path = os.path.dirname(__file__) + "\\tiktok-tricks-09.PNG" tiktok_image = tkinter.PhotoImage(file=img_path) resized_tiktok_img = tiktok_image.subsample(4,4) image_label = tkinter.Label(root, image=resized_tiktok_img) image_label.pack() # rank button rank_button = tkinter.Button(root, text="Get Ranking", command=calculate_ranking) rank_button.pack() # result result_label = tkinter.Label(root, text = "Your tiktok ranking is:") result_label.pack() # keep the UI running root.mainloop()
I keep getting this error, I have tried casting it to an integer, but it still doesn't work can anyone help: Do I need to change the top to str(tiktok_algorithm)
typeError: '>=' not supported between instances of 'str' and 'int'
-
Does sqlalchemy work on msys2 without pyodbc?
I'm trying to use sqlalchemy on windows10 in msys2 environment. However pyodbc which seems to be one of the sqlalchemy requirements does not seem to exist on https://packages.msys2.org/package/ where all other msys2 packages are available to download and install via pacman. I'm confused why sqlalchemy is even packaged and offered on that site if pyodbc is not available on msys2? What am I missing? By the way, using standard python on windows (not via msys2) does provide both sqlalchemy and pyodbc to install via pip and everything works as expected using those packages.
-
How to adjust variables in MS SQL Server through Python
I have several sql queries written in MS SQL Server and I used the following code to import them into Python using the pyodbc package.
import pyodbc import pandas as pd def conn_sql_server(file_path): '''Function to connect to SQL Server and save query result to a dataframe input: file_path - query file path output: df - dataframe from the query result ''' # Connect to SQL Server conn = pyodbc.connect('Driver= {SQL Server Native Client 11.0};' 'Server= servername;' 'Database = databasename;' 'Trusted_Connection=yes;') # run query and ouput the result to df query = open(file_path, 'r') df = pd.read_sql_query(query.read(), conn) query.close() return df df1 = conn_sql_server(filepath1) df2 = conn_sql_server(filepath2) df3 = conn_sql_server(filepath3)
In each SQL query, I have used DECLARE and SET to set the variables (variables are different in each SQL query). These variables need to be updated every year, so I am wondering if I could update them within python directly. I don't want to copy over the SQL scripts in python, I just want to adjust the variables. Anyway to do it?
My other question is, is there anyway to add a WHERE statement only in python? I'm asking this because df2 is a subset of df1. The restriction column isn't selected to show in the output, so I cannot do filterings in python after reading in df1. I could add that column in the df1 output and do more aggregations in Python, but that would largely increase the orginal data size and running time, so I prefer not to do it.
-
Format of ODBC connect not matching exactly what my script is asking
my code dbconnect command:
mysql-odbc://sct-mssql-db.c6p0dl1fqnlk.us-east-1.rds.amazonaws.com:1433/sct_mssql_db?mssql_user&schemaconversion
But Script actually want:
expected: db='dbtype[-odbc]://hostname[:port][/dbname[?user[&Pass]]]'
And I am getting error :
{"wrong_db_string": "Wrong format for dbconnect. Given: %s, expected: db='dbtype[-odbc]://hostname[:port][/dbname[?user[&Pass]]]'"
What is wrong with my above dbconnect command that it is not matching with expected result.