List comprehension not working as expected - python

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).

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',)]

separating dictionary values from inside of list

So currently I am working on extracting data from who.is, there were about 2000 links so I simply iterated over it with the function, but output is some what like this:
[{"email":"email#email.com", "Phone_no.":"+123456789", "more data":"more data", "even more data":"even more data"},
{"email":"email#email.com", "Phone_no.":"+123456789", "more data":"more data", "even more data":"even more data"},
{"email":"email#email.com", "Phone_no.":"+123456789", "more data":"more data", "even more data":"even more data"}]
the desired output is somewhat like:
["email#email.com","email#email.com","email#email.com"],["+123456789","+123456789","+123456789"]
You should iterate on each dictionnary of your list.
That will look like somthething like this :
email = []
phone_no = []
for d in data:
for key,value in d:
if(str(key) == 'email'):
email.append(value)
elif(str(key) == 'Phone_no.'):
phone_no.append(value)
else:
pass
So you have the email list with all email adresses and phone_no with all phone numbers
Assuming your data is in a variable called data:
emails = [d['email'] for d in data]
phone_numbers = [d['Phone_no.'] for d in data]
print(emails)
print(phone_numbers)
Output:
['email#email.com', 'email#email.com', 'email#email.com']
['+123456789', '+123456789', '+123456789']

How to substact a list of dictionaries (from an API) in a for loop to a new list

Here's what I've tried: I've made a function that returns all the product keys of every transaction (in a given time) from an API. I pass these key's in a for loop to info to get more specific data of every transaction in list of dictionaries and save the outcome to attrib. when I print attrib it returns just the last item, but if I print attrib inside the for loop it returns all items. How do I save all the data permanently, so I can access it by indexing the items in the list?
def product_id():
transactions = degiro.transactions(datetime(2020, 7, 30), datetime.now())
pid = [dic["productId"] for dic in transactions]
return pid
attrib = []
products = [num for num in product_id()]
for i in range(len(products)):
info = degiro.product_info(products[i])
attrib = ({k: v for k, v in info.items()})
print(pretty_json(attrib))
Click here fo a link to the API
This works:
transactions = degiro.transactions(datetime(2020, 7, 30), datetime.now())
pid = [dic["productId"] for dic in transactions]
return pid
print(product_id())
attrib = []
products = [num for num in product_id()]
for i in range(len(products)):
info = degiro.product_info(products[i])
attrib.append(info)
print(pretty_json(attrib))```

How to make two strings into a list in 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

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']

Categories