com = self.get_scan_companies()
for name in com:
k.append({'org_id' : None, 'keyword' : name['names']})
for domain in com:
k.append({'org_id' : None, 'keyword' : domain['domains']})
for ip in com:
k.append({'org_id' : None, 'keyword' : ip['Ips']})
com generates a dictionary of {id,'names','domains','Ips'}
Note: com has 4 items but I need the last 3 only.
I want to enhance the code to one for loop with 3 lines of appends as above:
for name,domain,ip in com:
k.append({'org_id' : None, 'keyword' : name['names']})
k.append({'org_id' : None, 'keyword' : domain['domains']})
k.append({'org_id' : None, 'keyword' : ip['Ips']})
Expected result is a list:
k=[{'org_id' : None, 'keyword' : name['names']}, {'org_id' : None, 'keyword' : domain['domains']},{'org_id' : None, 'keyword' : ip['Ips']}]
I understand the above does not generate the result! Thanks for your help in advance!
The three for loops are all iterating over the same data. Calling the iterators name, domain, or ip makes no difference. This would be equivalent to the following single for loop using iter_ as a generic iterator:
com = self.get_scan_companies()
for iter_ in com:
k.append({'org_id' : None, 'keyword' : iter_['names']})
k.append({'org_id' : None, 'keyword' : iter_['domains']})
k.append({'org_id' : None, 'keyword' : iter_['Ips']})
Related
I have a datastructure like this:
poll = {
'LINK' : {'MoonRaccoon' : 1, 'TheDirtyTree' : 1},
'ZRX' : {'MoonRaccoon' : 1, 'Dontcallmeskaface' : 1, 'TheDirtyTree' : 1},
'XRP' : {'Dontcallmeskaface' : 1},
'XLM' : {'aeon' : 1, 'Bob' : 1}
}
I want it to ultimately print like this ordered by the number of who have requested each, then ticker symbol alphabetically, then the users also alphabetically
!pollresults
ZRX : Dontcallmeskaface, MoonRaccoon, TheDirtyTree
LINK : MoonRaccoon, TheDirtyTree
XLM : aeon, Bob
XRP: Dontcallmeskaface
Anyone really good at sorting that could help me do this.. I'm really new to python and super rusty at coding in general.
Thanks for any help.
Dictionaries can't really be sorted, but for the purposes of printing, this can be done.
poll = {
'LINK' : {'MoonRaccoon' : 1, 'TheDirtyTree' : 1},
'ZRX' : {'MoonRaccoon' : 1, 'Dontcallmeskaface' : 1, 'TheDirtyTree' : 1},
'XRP' : {'Dontcallmeskaface' : 1},
'XLM' : {'aeon' : 1, 'Bob' : 1}
}
def print_polls(poll):
for ticker in sorted(poll, key=lambda t: sum(poll[t].values()), reverse=True):
print(f"{ticker}: {', '.join(sorted(poll[ticker]))}")
This will give you the output you're looking for
Here you get a oneliner:
print (sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True))
Output:
[('ZRX', {'MoonRaccoon': 1, 'Dontcallmeskaface': 1, 'TheDirtyTree': 1}), ('LINK', {'MoonRaccoon': 1, 'TheDirtyTree': 1}), ('XLM', {'aeon': 1, 'Bob': 1}), ('XRP', {'Dontcallmeskaface': 1})]
To pretty print:
lst = sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True)
for elem in lst:
print (elem[0],":"," ".join(elem[1].keys()))
And because I really like oneliners, everything in one line!
print ("\n".join([" : ".join([elem[0]," ".join(list(elem[1].keys()))]) for elem in sorted(poll.items(), key = lambda item : len(list(item[1].keys())), reverse = True)]))
Output:
ZRX : MoonRaccoon Dontcallmeskaface TheDirtyTree
LINK : MoonRaccoon TheDirtyTree
XLM : aeon Bob
XRP : Dontcallmeskaface
count the votes in poll, get d
sort d decreasingly
get poll result in the order of step 2, and handle sorting the name lists
d = [[k, len(v)] for k, v in poll.items()]
d.sort(key=lambda name_vote: (-name_vote[-1],name_vote[0]))
pollresults = [name + ' : ' + ', '.join(sorted(poll[name].keys(), key=str.lower)) for name,vote in d]
result:
>>> pollresults
['ZRX : Dontcallmeskaface, MoonRaccoon, TheDirtyTree', 'LINK : MoonRaccoon, TheDirtyTree', 'XLM : aeon, Bob', 'XRP : Dontcallmeskaface']
I am running into difficulties trying to create a modified key when manipulating a dictionary. Here the key needs to be changed from the original dict key to 'x' plus the dict key. How can that be done? My attempt is shown:
inventory = {k:updateMap(m,
{'partNumber': m['part'],
'partName': m['desc'],
'bbox': {
'xmin' : bboxes[k].x,
'xmax' : bboxes[k].x + bboxes[k].w,
'ymin' : bboxes[k].y,
'ymax' : bboxes[k].y + bboxes[k].h
}
}) for k,m in
['x%d' %k1,m1
for k1,m1 in inventoryRaw.items()]}
Here is the syntax error Unresolved reference m1:
How should the nested comprehension be modified?
The problem here is the tuple needs to be explicitly spelled out :
for k,m in [('x%s'%k1,m1)
This works:
inventory = {'x%s'%k:updateMap(m,
{'partNumber': m['part'],
'partName': m['desc'],
'objectClass': 'part',
'bbox': {
'xmin' : bboxes[k].x,
'xmax' : bboxes[k].x + bboxes[k].w,
'ymin' : bboxes[k].y,
'ymax' : bboxes[k].y + bboxes[k].h
}
}) for k,m in [('x%s'%k1,m1)
for k1,m1 in
inventoryRaw.items()]}
I am creating a rest-api using the Python+Flask_Restful combo, find it amazing.
Currently, i am allowing user to run a sql-query using the browser and it works fine, but the problem is, headers information is not displayed in the response.
Here is the code that i am using:
class RunCustomeSQL(Resource):
def get(self, enter_db_name, query):
if not os.path.isfile(enter_db_name+'.db'):
raise BadRequest("Database Doesn't Exist. Please select a valid database")
conn = sqlite3.connect(enter_db_name+'.db')
search_out = []
cursor = conn.execute(query)
row = None
for row in cursor:
search_out.append(row)
if not row: #This means empty response
raise BadRequest("No Results Found")
conn.commit()
conn.close()
return search_out
While, this code works great, it doesn't print the header values in the json-response. The current response is :
[
[
"dusiri_bibi",
"11",
"----------",
" srt/None ",
"14.30 MB",
"2017-12-13 23:43:54",
"C:/Test_Software/vc_redist.x64.exe"
],
]
Expected Output :
[
[
"Machine Name" : "dusiri_bibi",
"LABEL" : "11",
"PERMISSIONS" : "----------",
"USER" : " srt/None ",
"SIZE" : "14.30 MB",
"CREATED" : "2017-12-13 23:43:54",
"FILENAME" : "C:/Test_Software/vc_redist.x64.exe"
],
]
All the above text such as "machine name, label etc." are my table headers, I am not sure how to print them along with my output.
What if the user runs select user, size from table_name only
or
What if the user runs select * from table_name
In both scenario's, the output should display the table headers
Thanks
UPDATE #1 (25 April) : I managed to answer my first question and able to display a proper json response if the user selects the SELECT * statement in SQL but still facing issue with the second piece of it
Here is the answer to first part if anyone is looking for it : Using Regex
row = None
if re.search(r'(?<=SELECT)(.*)(?=FROM)',query, re.IGNORECASE).group(1) == ' * ':
for row in cursor:
search_out.append({'NAME' : row[0], 'LABEL_NUMBER' : row[1], 'PERM' : row[2], 'USER' : row[3] , 'SIZE' : row[4], 'DATE' : row[5], 'FILENAME' : row[6]})
if not row: #This means empty response
raise BadRequest("No Results Found")
Part II : Unanswered Query:
For the second piece, i now have two list :
list_1 : [[u'LABEL_NUMBER', u'PERM', u'FILENAME']]
list_2 : [(u'11', u'----------', u'C:/Test_Software/26.avi'), (u'11', u'----------', u'C:/Test_Software/6.avi'), (u'11', u'-rwx------', u'C:/Test_Software/Debug/Current_Frame1.avi'), (u'10', u'-rwxrwx---', u'C:/Windows/WinSxS/boxed-split.avi')]
As you can see, i have two list and i want to combine them into a dict to show the response like this:
[
{
LABEL_NUMBER : '11' ,
PERM : '-----------',
FILENAME : 'C:/Test_Software/26.avi'
},
...
....
......
{
LABEL_NUMBER : '10' ,
PERM : '-rwxrwx---',
FILENAME : 'C:/Windows/WinSxS/boxed-split.avi'
},
]
i am using the following code to do the same :
chunks = [list_2[idx:idx+3] for idx in range(0, len(list_2), 3)]
output = []
for each in chunks:
output.append(dict(zip(list_1, each)))
print(output)
But, this is failing with "TypeError: unhashable type: 'list'", i understand that lists are mutable and which is why i am getting this error but then how can i get the desired dict response? what am i doing wrong here?
You can use a list comprehension combined with zip for this:
list_1 = [[u'LABEL_NUMBER', u'PERM', u'FILENAME']]
list_2 = [(u'11', u'----------', u'C:/Test_Software/26.avi'), (u'11', u'----------', u'C:/Test_Software/6.avi'), (u'11', u'-rwx------', u'C:/Test_Software/Debug/Current_Frame1.avi'), (u'10', u'-rwxrwx---', u'C:/Windows/WinSxS/boxed-split.avi')]
d = [dict(zip(list_1[0], i)) for i in list_2]
Result:
[{'FILENAME': 'C:/Test_Software/26.avi',
'LABEL_NUMBER': '11',
'PERM': '----------'},
{'FILENAME': 'C:/Test_Software/6.avi',
'LABEL_NUMBER': '11',
'PERM': '----------'},
{'FILENAME': 'C:/Test_Software/Debug/Current_Frame1.avi',
'LABEL_NUMBER': '11',
'PERM': '-rwx------'},
{'FILENAME': 'C:/Windows/WinSxS/boxed-split.avi',
'LABEL_NUMBER': '10',
'PERM': '-rwxrwx---'}]
I am getting this weird behavior
test_dict = {'productDue' : ['foo'],'releaseDue' : ['bar']}
for attr, value in test_dict.items() :
print attr
and_args = [(and_(getattr(my_table,attr).in_(value)))]
This gives me :
>>> print and_(*and_args)
"my_table"."releaseDue" IN (:releaseDue_1)
Then when I switch the order :
test_dict = {'releaseDue' : ['bar'],'productDue' : ['foo']}
for attr, value in test_dict.items() :
print attr
and_args = [(and_(getattr(my_table,attr).in_(value)))]
I get :
>>> print and_(*and_args)
"TDC"."releaseDue" IN (:releaseDue_1)
I don't get it, I want to have "TDC"."releaseDue" IN (:releaseDue_1) AND "TDC"."productDue" IN (:productDue_1)
Help please
Thank you,
I've managed to do it with this :
and_args = [ (and_(getattr(my_table,attr).in_(value))) for attr, value in test_dict.items() ]
I'm no sqlalchemy expert, but is this hapenning because you are overwriting and_args with each pass of the loop?
Does something like
test_dict = {'productDue' : ['foo'],'releaseDue' : ['bar']}
and_args = []
for attr, value in test_dict.items() :
print attr
and_args.append( and_(getattr(my_table,attr).in_(value) )
all = and_(*and_args)
do the trick?
I have a function in a file which I am calling in a separate script (as shown below). Printing directly from the function works correctly, however when I try to return the value to the script it sends 'None'.
Any help would be appreciated.
Thanks
script:
import modules.functions as f
restype = 'THR'
atomtype = 'CA'
print f.AtomType(restype,atomtype)
function: (this is the part of the function which returns the value)
def AtomType(resName,atomType):
def threonine():
print 'well im here'
atoms = {'N' : 1,
'CA': 6,
'C' : 8,
'O' : 2,
'CB': 6,
'OG1': 1,
'CG2': 4,
}
print atoms[atomType]
return atoms[atomType]
residues = {'ALA' : hydrophobic,
'ARG' : arginine,
'ASN' : asparagine,
'ASP' : aspartate,
'CYS' : cysteine,
'GLN' : glutamine,
'GLU' : glutamate,
'GLY' : hydrophobic,
'HIS' : histidine,
'ILE' : hydrophobic,
'LEU' : hydrophobic,
'LYS' : lysine,
'MET' : methionine,
'PHE' : phenylalanine,
'PRO' : proline,
'SER' : serine,
'THR' : threonine,
'TRP' : tryptophan,
'TYR' : tyrosine,
'VAL' : hydrophobic,
}
residues[resName]()
and the output I get is:
well im here
6
None
edit: added entire function
Here's a guess: AtomType calls threonine, but doesn't return its return value.