【问题标题】:TinyDB how to updateTinyDB如何更新
【发布时间】:2019-07-30 20:44:51
【问题描述】:

如果我想更新一个特定的密钥,我该怎么做?为什么我不能用字典方法直接更新?

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())

输出:

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

预期:

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

虽然使用Query() 可能有用,但以后我可能会有很多类似的记录,并且为每个键设置条件可能会很麻烦。我想尝试使用记录本身作为条件,只需更改一个键。

【问题讨论】:

    标签: python tinydb


    【解决方案1】:

    要更新文档中的值,请使用update method

    在你的例子中:

    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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多