returned dictionary value is 'None' python - python

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.

Related

Python one 'for' loop, multiple dictionary appends

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

json response to python variable

In the following code (a html response), do I need to remove the "M18.high_52 = {" in the beginning and the "}" (in the very end) in order to assign it under a python json variable? Thanks!
Update:
I just want to get the securityCode and securityShortName. Both already done and I just want to see it could be simply it and not using the
x = r.text.replace("M18.high_52 = " ,"")
to assign to json.
M18.high_52 = {
"stockBeans" : [
{
"securityCode" : "00176",
"yearHigh" : "0.218",
"yearLow" : "0.121",
"percentageChange" : 14.737,
"priceChange" : 0.028,
"securityShortName" : "SUPERACTIVE GP",
"securityNameGCCS" : "先機企業集團",
"previousClosingPrice" : "0.19",
"nominalPrice" : "0.218",
"sharesTraded" : "400000",
"turnover" : "80726",
"highPrice" : "0.22",
"lowPrice" : "0.19"
}
,{
"securityCode" : "00532",
"yearHigh" : "0.71",
"yearLow" : "0.49",
"percentageChange" : 20.339,
"priceChange" : 0.12,
"securityShortName" : "WKK INTL (HOLD)",
"securityNameGCCS" : "王氏港建國際",
"previousClosingPrice" : "0.59",
"nominalPrice" : "0.71",
"sharesTraded" : "1122000",
"turnover" : "749480",
"highPrice" : "0.72",
"lowPrice" : "0.63"
}
],
"stockBeans.size" : 37
}
Update:
import json
import requests
###
def update52wHigh():
r = requests.get("http://money18.on.cc/js/real/52highlow/high_securityCode_b5_asc.js")
r.encoding = 'big5-hkscs'
x = r.text.replace("M18.high_52 = " ,"")
j = json.loads(x)
print (j["stockBeans"][0]["securityNameGCCS"])
importList = []
stockList = []
x=0
for stockBean in j["stockBeans"]:
stockName = stockBean["securityNameGCCS"]
stockNo = stockBean["securityCode"]
stockPrice = stockBean["nominalPrice"]
stockTurnover = stockBean["turnover"]
stockPercentageChange = stockBean["percentageChange"]
print (stockNo + " " +stockName)
if float(stockPrice) > 1:
stockList.append([])
stockList[x].append(stockNo)
stockList[x].append(stockPrice)
importList.append((stockNo,stockName,stockPrice,stockTurnover,stockPercentageChange))
x=x+1
update52wHigh()
No need to remove anything..You already have a response
This show work
import json
import requests
string_res = response.read().decode('utf-8')
json_object = json.loads(string_res)

Sorting multi-dictionary in python

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

Syntax to modify the keys inside a dictionary for-comprehension

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()]}

how to combine different complex list with python

BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"],
"Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}
I want to combine this data
like this...
BIG = {"Brand" : [ {"Clothes" : ["T-shirts", "pants"]}, {"Watch" : ["gold", "metal"]} ],...
Please tell me how to solve this problem.
First off, those are dictionaries and not lists. Also, I do no know your intention behind merging two dictionaries in that representation.
Anyways, if you want the output to be exactly as you mentioned, then this is the way to do it -
BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"],"Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}
for key,values in BIG.items(): #change to BIG.iteritems() in python 2.x
newValues = []
for value in values:
if value in SMA:
newValues.append({value:SMA[value]})
else:
newValues.append(value)
BIG[key]=newValues
Also, BIG.update(SMA) will not give you the right results in the way you want them to be.
Here is a test run -
>>> BIG.update(SMA)
>>> BIG
{'Watch': ['gold', 'metal'], 'Brand': ['Clothes', 'Watch'], 'Skin': ['lotion', 'base'], 'Beauty': ['Skin', 'Hair'], 'Clothes': ['T-shirts', 'pants'], 'Hair': ['shampoo', 'rinse']}
Firstly, you need to iterate on first dictionary and search the pair of key in second dictionary.
BIG = { "Brand" : ["Clothes" , "Watch"], "Beauty" : ["Skin", "Hair"] }
SMA = { "Clothes" : ["T-shirts", "pants"], "Watch" : ["gold", "metal"], "Skin" : ["lotion", "base"] , "Hair" : ["shampoo", "rinse"]}
for key_big in BIG:
for key_sma in BIG[key_big]:
if key_sma in SMA:
BIG[key_big][BIG[key_big].index(key_sma)] = {key_sma: SMA.get(key_sma)}
print BIG
The result of code:
>>> {'Brand': [{'Clothes': ['T-shirts', 'pants']}, {'Watch': ['gold', 'metal']}], 'Beauty': [{'Skin': ['lotion', 'base']}, {'Hair': ['shampoo', 'rinse']}]}

Categories

Resources