How to make two strings into a list in Python? - python

I have two strings I want to have in a list type:
str1 = "select something from tbl"
str2 = "select somethingElse from tbl2"
I want this as my output:
list = ['select something from tbl','select somethingElse from tbl2']
so I can pass each string into a for loop:
for statement in list:
#do something and it executes the statements passed
Here's additional context:
list = [soql_w_compoundedAttributes, soql_wo_compoundedAttributes]
for item in list:
final_df = []
print(item)
df = spark.read.format("com.springml.spark.salesforce") \
.option("login", "https://test.salesforce.com") \
.option("username", user) \
.option("password", pass) \
.option("soql",item) \
.load()
final_df.append(df)
sfDF = reduce(DataFrame.unionAll, final_df)
I get a REASON BAD REQUEST ERROR and when I look at my print(item) results i see that both sql statements are being passed at the same time. Can anyone explain why?

Simply:
myList = [str1, str2]
Then:
print(myList)

str1 = "select something from tbl"
str2 = "select somethingElse from tbl2"
list1 = [str1, str2]
for item in list1:
#the rest of the code goes here

Related

Removing a word from a list

So I got a list with names and I'm trying to delete the names out of the list. but somehow it doesn't work the way I want it to. Any help would be much appreciated. I think the problem is something with the replace function but I'm not sure.
Funtion:
#pyqtSlot(str, str)
def rapportmail (self, email, wachtwoord):
credentials = Credentials(email, wachtwoord)
acc = Account(email, credentials=credentials, autodiscover=True)
cursor.execute("SELECT DISTINCT Naam FROM Klant")
updatedklant = str(cursor.fetchall())
test = updatedklant
for item in acc.inbox.all().order_by('-datetime_received')[:500]:
inboxmail = str(item.sender).split("'")
currentinboxmail = inboxmail[3]
cursor.execute("SELECT DISTINCT Klant FROM Mail WHERE Mail=?", currentinboxmail)
currentklant = str(cursor.fetchall())
remove_characters = ["(",")",",","]","["]
for characters in remove_characters:
currentklant = currentklant.replace(characters, "")
if currentklant not in updatedklant:
for idx, elem in enumerate(test):
if elem[0] == currentklant:
test.pop(idx)
It is prints this now:
currentklant == 'alerttestting'
test == [('alerttestting', ), ('emretestingsystems', ), ('jarnodebaas', ),('yikes', )]
Result should be:
currentklant == 'alerttestting'
test ==[('emretestingsystems', ), ('jarnodebaas', ),('yikes', )]
Never, ever convert the result of cursor.fetchall() to a str and then strip out the characters you don't like. This is going to be a huge source of trouble. What if the name itself contains one of those characters, like "Bond, James" or "O'Brien"?
Keep it as a Python object (probably a list or tuple) and process it in that form.
In this case you probably wanted something like this:
...
updatedklant = cursor.fetchall() # No more str()
...
currentklant = cursor.fetchall()) # No more str()
...
test = [klant for klant in updatedklant if klant != currentklant]
should work perfectly
[('alerttestting',), ('emretestingsystems',), ('jarnodebaas',), ('yikes',)]
if __name__ == "__main__":
currentklant = 'alerttestting'
test = [('alerttestting',), ('emretestingsystems',), ('jarnodebaas',), ('yikes',)]
for idx, elem in enumerate(test):
if elem[0] == currentklant:
test.pop(idx)
[('emretestingsystems',), ('jarnodebaas',), ('yikes',)]

Mysql json.dump() line break indentation for viewing

I am using the following line of code for executing and printing data from my sql database. For some reason that is the only command that works for me.
json_string = json.dumps(location_query_1)
My question is that when I print json_string it shows data in the following format:
Actions.py code:
class FindByLocation(Action):
def name(self) -> Text:
return "action_find_by_location"
def run (self, dispatcher: CollectingDispatcher,
tracker: Tracker,
doman: Dict[Text, Any])-> List[Dict[Text,Any]]:
global flag
location = tracker.get_slot("location")
price = tracker.get_slot("price")
cuisine = tracker.get_slot("cuisine")
print("In find by Location")
print(location)
location_query = "SELECT Name FROM Restaurant WHERE Location = '%s' LIMIT 5" % location
location_count_query = "SELECT COUNT(Name) FROM Restaurant WHERE Location = '%s'" % location
location_query_1 = getData(location_query)
location_count_query_1 = getData(location_count_query)
if not location_query_1:
flag = 1
sublocation_view_query = "CREATE VIEW SublocationView AS SELECT RestaurantID, Name, PhoneNumber, Rating, PriceRange, Location, Sublocation FROM Restaurant WHERE Sublocation = '%s'"%(location)
sublocation_view = getData(sublocation_view_query)
dispatcher.utter_message(text="یہ جگہ کس ایریا میں ہے")
else:
flag = 0
if cuisine is None and price is None:
json_string = json.dumps(location_query_1)
print(isinstance(json_string, str))
print("Check here")
list_a=json_string.split(',')
remove=["'",'"','[',']']
for i in remove:
list_a=[s.replace(i, '') for s in list_a]
dispatcher.utter_message(text="Restaurants in Location only: ")
dispatcher.utter_message(list_a)
What should I do se that the data is showed in a vertical list format (new line indentation) and without the bracket and quotation marks? Thank you
First of all, have you tried reading your data into a pandas object? I have done some programs with a sqlite database and this worked for me:
df = pd.read_sql_query("SELECT * FROM {}".format(self.tablename), conn)
But now to the string formatting part:
# this code should do the work for you
# first of all we have our string a like yours
a="[['hallo'],['welt'],['kannst'],['du'],['mich'],['hoeren?']]"
# now we split the string into a list on every ,
list_a=a.split(',')
# this is our list with chars we want to remove
remove=["'",'"','[',']']
# now we replace all elements step by step with nothing
for i in remove:
list_a=[s.replace(i, '') for s in list_a]
print(list_a)
for z in list_a:
print(z)
The output is then:
['hallo', 'welt', 'kannst', 'du', 'mich', 'hoeren?']
hallo
welt
kannst
du
mich
hoeren?
I hope I could help.

Python return value without inverted commas

I have csv file:
shack_imei.csv:
shack, imei
F10, "5555"
code:
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
print shack
def get_imei_from_entered_shack(shack):
for key, value in my_dict.iteritems():
if key == shack:
return value
list = str(get_imei_from_entered_shack(shack))
print list
which gives me "5555"
But I need this value in a list structure like this:
["5555"]
I've tried a lot of different methods, and they all end up with extra ' or""
EDIT 1:
new simpler code:
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
imei = my_dict[shack]
print imei
"5555"
list(imei) gives me ['"5555"'], I need it to be ["5555"]
You can change your "return" sentence:
shack = raw_input('Enter Shack:')
print shack
def get_imei_from_entered_shack(shack):
for key, value in my_dict.iteritems():
if key == shack:
return [str(value)]
list = get_imei_from_entered_shack(shack)
print list
As far as I understand, you want to create a list containing the returned string, which you do with [ ]
list = [str(get_imei_from_entered_shack(shack))]
There are a few problems with this code, which are too long to tackle in comments
my_dict
my_dict = dict(reader) works only well if this csv is a collection of keys and values. If there are duplicate keys, this might give some problems
get_imei_from_entered_shack
Why this special method, instead of just asking my_dict the correct value. Even if you don't want it to trow an Exception when you ask for a shack that doesn't exists, you can use the dict.get(<key>, <default>) method
my_dict(shack, None)
does the same as your 4-line method
list
don't name variables the same as builtins
list2
if you want a list, you can do [<value>] or list(<value>) (unless you replaced list with your own variable assignment)
reader = csv.reader(open("shack_imei.csv", "rb"))
my_dict = dict(reader)
shack = raw_input('Enter Shack:')
imei = my_dict[shack]
imei = imei.replace('"',"")
IMEI_LIST =[]
IMEI_LIST.append(imei)
print IMEI_LIST
['5555']

Python list is not being appended to if value found in another list

I have some code that is supposed to parse some sql statements.
For some reason the cmd_ordered_list only seems to contain 'update' rather than all the other statements. It seems to me this line is not working as it should:
if(cmd in def_ordered_list):. Am I missing something obvious here?
sql_statements = {}
sql_select = {'select': 'select, *, from, where, and'}
sql_delete = {'delete': 'delete, from, where, and'}
sql_update = {'update': 'update, index, set, where, and'}
sql_insert = {'insert': 'insert, into, source'}
sql_statements.update(sql_select)
sql_statements.update(sql_delete)
sql_statements.update(sql_update)
sql_statements.update(sql_insert)
cmd = "update index employees set col = 'Hello'"
cmd_list = cmd.split()
first_cmd = cmd_list[0] # update
def_ordered_list = sql_statements[first_cmd].split(",")
cmd_ordered_list = []
for cmd in cmd_list:
if(cmd in def_ordered_list):
cmd_ordered_list.append(cmd)
print def_ordered_list
print cmd_ordered_list # only contains 'update' ?? why?
Your input contains spaces:
>>> 'update, index, set, where, and'.split(',')
['update', ' index', ' set', ' where', ' and']
Note the spaces before index, set, where and and. You never account for those spaces when doing list membership; you should probably strip those first. Or better yet, not store those options as a string in the first place.
If you stored sets in your sql_statements mapping you avoid issues with splitting, and as an extra bonus make membership testing way faster than when using lists:
sql_statements = {
'select': {'select', '*', 'from', 'where', 'and'},
'delete': {'delete', 'from', 'where', 'and'},
'update': {'update', 'index', 'set', 'where', 'and'},
'insert': {'insert', 'into', 'source'},
}
Creating the ordered list is then as simple as:
cmd = "update index employees set col = 'Hello'"
cmd_list = cmd.split()
cmd_ordered_list = [s for s in cmd_list[] if s in sql_statements[cmd_list[0]]]

List comprehension not working as expected

The following list comprehension users = [item for item in out.split() if domain in item and userl in item] as it suggests it should only add users to the users() if they meet the domain and userl criteria. However I'm getting empty results in the sorted_list. Can anyone suggest why?
domain = 'domainanme'
user_list = [test1, test2, test3]
new_list = []
for userl in user_list:
try:
out = subprocess.check_output(["tasklist", "/V", "/FO", "List", "/FI", "USERNAME eq {0}\{1}" .format(domain, userl)], stderr=subprocess.STDOUT)
users = [item for item in out.split() if domain in item and userl in item]
sorted_list = set(users)
print sorted_list
if sorted_list != None: # this was an attempted to remove the EMPTY items
for name in sorted_list:
print name
new_list.append(name)
else:
pass
print name output
set([])
set([])
set([])
This is what the output looks like:
The domain name in the output is uppercased; make sure you take that into account. Normalize the case for both to ensure a case-insensitive match:
users = [item for item in out.split() if domain.upper() in item.upper() and userl in item]
I'd parse that output a little more intelligently as the above can easily lead to false-positives (a process name that has both the domain and username in it, even as overlapping text, would match too).

Categories