Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TinyDB how to update

Tags:

python

tinydb

If I want to update a specific key how would I do so? Why can't I do a direct update with dictionary methods?

db = TinyDB(sys.argv[1]) #assume empty
db.insert({'a':'1','b':'2'})

for record in db:
   if True:
      record['a'] = 2

print(db.all())

Output:

({'a':'1','b':'2'})

Expected:

({'a':'2','b':'2'})

While using Query() may be useful, in the future I may have a lot of similar records and setting conditions for each key may be a hassle. I want to try to use the record itself as the condition and just change a single key.

like image 699
PhantomQuest Avatar asked Sep 19 '25 21:09

PhantomQuest


1 Answers

To update values inside document, use update method.

In your example:

from tinydb import TinyDB, Query

db = TinyDB('db.json')
db.insert({'a': '1', 'b': '2'})

print(db.all())

# Find all documents (dict objects) that contain 'a' key
# and set value of key 'a' to 2
db.update({'a': 2}, Query().a.exists())

print(db.all())
like image 98
Dinko Pehar Avatar answered Sep 21 '25 14:09

Dinko Pehar