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

10th Dec 2020, 9:21 AM
CutieRei
CutieRei - avatar
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
10th Dec 2020, 9:58 AM
Slick
Slick - avatar
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
10th Dec 2020, 9:47 AM
Slick
Slick - avatar
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
10th Dec 2020, 9:50 AM
CutieRei
CutieRei - avatar
0
10th Dec 2020, 9:52 AM
Slick
Slick - avatar
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 }
10th Dec 2020, 9:53 AM
CutieRei
CutieRei - avatar
0
there's always a better way. Just be happy it works
10th Dec 2020, 9:54 AM
Slick
Slick - avatar
0
okay then, also should i catch exception or do some checks to avoid errors
10th Dec 2020, 9:54 AM
CutieRei
CutieRei - avatar
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
10th Dec 2020, 9:56 AM
Slick
Slick - avatar
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
10th Dec 2020, 9:57 AM
CutieRei
CutieRei - avatar
0
hm alright, thanks for the heads up
10th Dec 2020, 10:00 AM
CutieRei
CutieRei - avatar
0
thats not the issue here but ok
10th Dec 2020, 9:32 PM
CutieRei
CutieRei - avatar