i have a nested dictionary in the form of:
self.emoji_per_word = {0: {'worte': 0, 'emojis': 0, '#': 0}}
Now i need to add more sub dictionaries to this as my program runs. I do this:
worte = 0
emoji = 0
# some code that assigns values to the 2 variables and creates the time_stamp variable
if time_stamp in self.emoji_per_word:
self.emoji_per_word[time_stamp]['worte'] = self.emoji_per_word[time_stamp]['worte'] + worte
self.emoji_per_word[time_stamp]['emojis'] = self.emoji_per_word[time_stamp]['emojis'] + emojis
else:
self.emoji_per_word[time_stamp]['worte'] = worte
self.emoji_per_word[time_stamp]['emojis'] = emojis
As you can see, i try to the test if the key time_stamp already exists and if yes, update the value with the new data. If not i want to create the key time_stamp and assign it a inital value. However im getting a Key Error once the programm goes past the inital value (see top).
Exception in thread Video 1:
Traceback (most recent call last):
File "C:\Anaconda\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\MA\Code\jsonparser_v2\jsonparser_v2.py", line 418, in run
self.process_json()
File "C:\MA\Code\jsonparser_v2\jsonparser_v2.py", line 201, in process_json
self.emoji_per_word[time_stamp]['worte'] = worte
KeyError: 1
What I want in the end is something like this:
self.emoji_per_word = {0: {'worte': 20, 'emojis': 5, '#':0.25}, 1: {'worte': 20, 'emojis': 5, '#':0.25}}
What am I doing wrong here?
You're getting the error because self.emoji_per_word[time_stamp] doesn't exist when time_stamp != 0 so you need to create the dictionary first before assigning values to it, like so:
else:
self.emoji_per_word[time_stamp] = {}
self.emoji_per_word[time_stamp]['worte'] = worte
self.emoji_per_word[time_stamp]['emojis'] = emojis
Related
If anyone can help me to get a value from a json response. I intend to get only the first incidence of id where the type is CLIENTREF.
I am reading a list to get some values to do a GET and check if the response is other than null "".
This is the JSON structure:
This is my code so far
def checkParent(list):
for item in list:
cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}"
r = requests.get(cdwParenturl).json()
jsonpath_expression = parse("$..identifier[*]")
# $..identifier[?(#.type == 'CLIENTREF')].id
parentId = []
for match in jsonpath_expression.find(r):
# print(f"match id: {match.value}")
thisdict = match.value
if thisdict["type"] == "CLIENTREF":
# print(thisdict["id"])
parentId.append(thisdict["id"])
elif thisdict["id"] == "":
print(colored(f"The parent {item} does not have ultimateParent", "red"))
print(colored(f"All counterparties have parent", "green"))
checkParent(r_mheu_trade)
print(f "match id: {match.value}") I get this, What I need is the first id related to the type: CLIENTREF
The error that appears on my console is this:
Traceback (most recent call last):
File "h:\DESKTOP\test_check\checkCounterpartie.py", line 114, in <module>
checkParent(r_mheu_trade)
File "h:\DESKTOP\test_check\checkCounterpartie.py", line 106, in checkParent
if thisdict["type"] == "CLIENTREF":
KeyError: 'type'
With the help of pyzer I found a solution to my problem. This is how the code looks like:
# Request to get all UltimateParent
def checkParent(murex):
for item in murex:
cdwParenturl = f"http://cdwu/cdw/counterparties/{item}/?yyyy-mm-dd={dateinplay}"
r = requests.get(cdwParenturl).json()
clientref = r[0]["riskUltimateParent"]["identifier"][1]
if clientref == "":
print(colored(f"The parent {item} does not have ultimateParent", "red"))
else:
print(colored(f"All counterparties have parent", "green"))
checkParent(r_mheu_trade)
I'm completing a task I was given by my Teacher and it asks for a modular program so I tried to create some def modules but I can't figure out how to pass parameters between them.
Here's the code so far. (I don't know how to make it much neater on the site sorry.)
import string
def Datawrite ():
forename = []
surname = []
distance = []
data = open("members.txt","r")
for line in data:
value = line.split(',')
forename.append(value[0])
surname.append(value[1])
distance.append(value[2])
data.close()
def FarthestWalker(distance):
farthest_walk = distance[0]
for counter in range(len(distance)):
if float(distance[counter]) >= float(farthest_walk):
farthest_walk = distance[counter]
farthest_walk = float(farthest_walk)
Calcandstore()
def Calcandstore(forename,surname,distance,farthest_walk):
Results = open("Results.txt","w+")
Results.write("The prize winnning memberes are:\n")
seventy = 0.7*farthest_walk
Winning = []
for count in range(len(distance)):
if float(distance[count]) >= float(seventy):
Winning.append([count])
for count in range(len(Winning)):
Results.write(forename[count]+":")
Results.write(surname[count]+":")
Results.write(distance[count])
Results.close()
Datawrite()
FarthestWalker(distance)
Calcandstore(forename,surname,distance,farthest_walk)
When I run the code it returns this.
Traceback (most recent call last):
File "E:\Assignment\Test.py", line 58, in <module>
FarthestWalker(distance)
File "E:\Assignment\Test.py", line 29, in FarthestWalker
farthest_walk = distance[0]
IndexError: list index out of range
I have been tinkering with this for a few days now and I can't get the thing to work.
Here are some issues:
1) Datawrite doesn't return anything so the lists you're building are lost in the ether.
2) You call FarthestWalker with distance which is never initialized.
3) You call Calcandstore with values that are not initialized.
To pass values from functions you need to return values and declare them. For example:
def make_cat():
return 'Cat'
def print_animal(animal):
print(animal)
c = make_cat()
print_animal(c)
I'm trying to create multiple graph and using Dijkstra's. However I'm getting an error: NoneType object has no attribute 'set_distance'. The very strange thing is that the first item in the list ['2001A1'] runs fine but then when the list is longer than 1 it just crashes with that error. If I run the code with just one item in the list, it works as well. Printing out my vertices, the graph shows that there are vertex instances for all of my keys... Is there something that I'm missing? Why can't I do this more than one times? Why is it that when I try to get my vertex object I get returned null when my map of vertices has key {1:(Vertex object)}?
def create_graph(q,y,pop,psub,a,b,c):
a = Graph(q,y,pop,psub,a,b,c)
for i in range(0,9):
a.add_vertex(i)
return a
def run_dijkstras(graph,data):
for i in data:
try:
year = int(i[0:4])
print year
except:
print i
rest = i[4:]
graph.add_edge(year,rest)
quarter = graph.get_quarter()
print graph.vert_dict
print quarter
print graph.get_vertex(quarter)
print str(graph.get_vertex(quarter))
dijkstra(graph,graph.get_vertex(quarter))
target = graph.get_vertex(quarter+4)
path = [target.get_id()]
shortest(target, path)
if len(path) == 1:
path = "NULL"
return [path,(str(target.get_distance())),data]
i = 2001
for j in range(1,5):
for datacombo in ([['2001A1'], ['2001R4']]):
a = run_dijkstras(create_graph(j,i,10,1,.05,-.1,-.5),datacombo)
result,score = a[0],a[1]
if score == 9999999999999:
score = "NULL"
score = score.ljust(15)
datacombo = generate_matrix(datacombo)
i = str(i).ljust(5)
j = str(j).ljust(2)
datacombo=re.sub("\[|\]|'","",str(datacombo)).ljust(100)
result=re.sub("\[|\]|'","",str(result)).ljust(25)
print(i,j,result,score,datacombo)
ERROR LOG:
{0: <__main__.Vertex instance at 0x0000000002439DC8>, 1: <__main__.Vertex instan
ce at 0x0000000002439CC8>, 2: <__main__.Vertex instance at 0x0000000002439C88>,
3: <__main__.Vertex instance at 0x0000000002439C08>, 4: <__main__.Vertex instanc
e at 0x0000000002439E48>, 5: <__main__.Vertex instance at 0x0000000002439E88>, 6
: <__main__.Vertex instance at 0x0000000002439EC8>, 7: <__main__.Vertex instance
at 0x0000000002439F08>, 8: <__main__.Vertex instance at 0x0000000002439F48>}
1
None
None
Traceback (most recent call last):
File "dijkstras3.py", line 282, in <module>
a = run_dijkstras(create_graph(j,i,10,1,.05,-.1,-.5),datacombo)
File "dijkstras3.py", line 190, in run_dijkstras
dijkstra(graph,graph.get_vertex(quarter))
File "dijkstras3.py", line 132, in dijkstra
start.set_distance(0)
AttributeError: 'NoneType' object has no attribute 'set_distance'
i am trying to return a value from db and getting this error.I tried the previously answered questions here,but no luck.Can anyone help me?
#frappe.whitelist()
def generate_barcode():
last_barcode = frappe.db.sql("""\
select MAX(barcode) from `tabItem` """)
if last_barcode:
last_barcode = last_barcode + 1
else:
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
random.shuffle(x)
last_barcode = x[0]
return {'last_barcode':last_barcode}
adding traceback:
Traceback (innermost last):
File "/home/adminuser/frappe-bench-hitech/apps/frappe/frappe/app.py", line 49, in application
response = frappe.handler.handle()
File "/home/adminuser/frappe-bench-hitech/apps/frappe/frappe/handler.py", line 66, in handle
execute_cmd(cmd)
File "/home/adminuser/frappe-bench-hitech/apps/frappe/frappe/handler.py", line 89, in execute_cmd
ret = frappe.call(method, **frappe.form_dict)
File "/home/adminuser/frappe-bench-hitech/apps/frappe/frappe/__init__.py", line 531, in call
return fn(*args, **newargs)
File "/home/adminuser/frappe-bench-hitech/apps/erpnext/erpnext/stock/doctype/item/item.py", line 405, in generate_barcode
last_barcode = last_barcode + 1
TypeError: can only concatenate tuple (not "int") to tuple
I don't know what "frappe" is and you failed to post the full traceback so we can only try and guess, but very obviously frappe.db.sql("select MAX(barcode) fromtabItem") returns a tuple (which is what I'd expect from a select on a SQL db), so you want something like:
row = frappe.db.sql(
"select MAX(barcode) from `tabItem`"
)
last_barcode = row[0]
if last_barcode:
last_barcode = last_barcode + 1
As a side note: if you want a random int between 0 and 9 (included), it's spelled random.randint(0, 9)
I somehow got the answer.Thanks for everyone's help.
#frappe.whitelist()
def generate_barcode():
last_barcode_auto = frappe.db.sql("""\
select MAX(barcode) from `tabItem` """)
if last_barcode_auto[0][0] :
last_barcode = last_barcode_auto[0][0]
final_barcode= last_barcode+1
else:
final_barcode=random.randrange(100001, 100000000000, 2)
return {'final_barcode':final_barcode}
The error message is saying that last_barcode is a tuple. Use last_barcode[0] to retrieve the first value (which in this case would be the only value because you selected one column).
if last_barcode:
last_barcode = last_barcode[0] + 1
I'm testing the following function:
def getDataMapOfFirstLine(line):
datamap = {}
for item in line:
hierarchy = item.split('^')
partialmap = datamap
i=0
for node in hierarchy:
partialmap = partialmap.setdefault(node, i)
i += 1
return datamap
It should create a dictionary out of the first line of a csv-file, that looks like this:
nummer;such;ans;bverb^konum;bverb^namebspr;bverb^bank^iident;
1213;HANS;Hans Dominik;111000222;Hans' account; DE2145432523534232;
1444555;DIRK;Dirk Daniel;13300002;Dirk's account; DE2134634565462352;
As you see these circumflex-signs in each semicolon-separated string are something like a join in SQL. If I execute it, I get this error:
Traceback (most recent call last):
File "./importtool.py", line 173, in <module>
main()
File "./importtool.py", line 38, in main
analyseImportFile(importfile, parser, options)
File "./importtool.py", line 119, in analyseImportFile
datamap = getDataMapOfFirstLine(line)
File "./importtool.py", line 149, in getDataMapOfFirstLine
partialmap = partialmap.setdefault(node, i)
AttributeError: 'int' object has no attribute 'setdefault'
If I replace the i in the setdefault-function by {} I get no error:
{'bverb': {'namebspr': {}, 'konum': {}, 'bank': {'iident': {}}}, 'such': {}, 'ans': {}}
This is nearly, what I want, but instead of the {} I would like to get a column-number.
I just don't get what is wrong. I tried this in interactive mode:
>>> mydict = {'foo': "Hallo", 'bar': 5}
>>> mydict.setdefault("sth", 12)
12
>>> print mydict
{'sth': 12, 'foo': 'Hallo', 'bar': 5}
As you see, this works...
I appreciate every help. Thanks in advance!
Your problem is this line:
partialmap = partialmap.setdefault(node, i)
dict.setdefault returns the thing that was set (or what was already there). In this case, it's an integer so you're setting partialmap to an int. You can probably just not grab the return value (which is what you've done in the interactive terminal BTW):
partialmap.setdefault(node, i)