0
Is this a nice way to update database when a value in a dictionary is edited or set
here is the code i made so far with asyncpg and asyncio https://code.sololearn.com/c5FZf1MAbkAi/?ref=app my goal is to update the value when a key in dictionary is changed, like `dict["key"] = "value"` it would insert to the database if the key doesn't exists and update the value in the database if key already exists
11 ответов
+ 1
And if you want, you should check out the json library in python. it converts dictionaries to and from json format. I peraonally just find dictionaries easier to work with, but again, its preference
Alvreius Dante and i personally go with the second one way more often
0
you can use get()
say you wanted to add 5 buildings to the database:
# checks if the key is availible
if dict.get("buildings",0) == 0:
# if key not availible, make it
dict["buildings"] = 5
else:
# if key availible, add to existing
dict["buildings"] += 5
0
that's exactly the reason why im making a subclass, to automatically add to database when item is set from the dictionary like dict["hi"] = "hello", now the table in my database will be
name | description
---------+------------------
hi | hello
0
right, soo whats the question?
https://code.sololearn.com/czEhUVvDsCai/?ref=app
0
is this a good way to make it or is there a better way to do it
also Slick the value can be 0 since its storing integers like this json format
{
str: int,
str: int
}
0
there's always a better way. Just be happy it works
0
okay then, also should i catch exception or do some checks to avoid errors
0
You can, or you could save the error handling for the program you're making with that class. It's whatever your preference is
0
Oh i meant in the key checking like
try:
self[key]
#update
except KeyError:
#insert
or
if self.get(key) is None:
#insert
else:
#update
0
hm alright, thanks for the heads up
0
thats not the issue here but ok