3

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.

PhantomQuest
  • 349
  • 4
  • 12

1 Answers1

1

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())
Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57