You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python命令行中使用TinyDB删除指定数据?

Fixing the Delete Functionality for Your TinyDB Setup

Hey there! Let's get that delete feature working properly. Right now your code is successfully finding entries that match your criteria, but it's not actually removing them from the database. Here's how to tweak your code to make it delete targeted entries:

Updated Code Snippet

elif command == 'del' or command == 'delete':
    Cat_Del = input('Which Category do you wanna delete: ')
    Name_Del = input('Whats the name ')
    from tinydb import Query
    Item = Query()
    
    # Use TinyDB's remove() method with combined search criteria
    deleted_entries = db.remove((Item['Category'] == Cat_Del) & (Item['Naam'] == Name_Del))
    
    # Give clear feedback to the user
    if deleted_entries:
        print(f"Successfully deleted {len(deleted_entries)} entry(ies)!")
    else:
        print("Oops, no entries matched your category and name.")
    
    # Optional: Show updated database to confirm changes
    print("\nCurrent database content:")
    print(db.all())

Key Changes Explained

  • Replace search() with remove(): The search() method only returns matching entries, but remove() does the actual deletion and gives you back the list of entries it deleted—perfect for confirming what was removed!
  • Fix the logical operator: TinyDB uses & (ampersand) for "AND" in queries instead of Python's regular and. Using and would break the query logic because it evaluates to a boolean, whereas & keeps the query conditions intact for TinyDB to parse correctly.
  • Add user feedback: Now you'll know right away if the deletion worked or if there were no matching entries—no more guessing!

Test It Out

With your sample database:

{"_default": {"1": {"Category": "Fruit", "SubCategory": "zoet", "Naam": "appel", "Cost": "$5"}, "2": {"Category": "Fruit", "SubCategory": "zoet", "Naam": "banaantje", "Cost": "$10"}}}

If you input Fruit as the category and appel as the name, the code will delete the first entry. Your database will then look like this:

{"_default": {"2": {"Category": "Fruit", "SubCategory": "zoet", "Naam": "banaantje", "Cost": "$10"}}}

内容的提问来源于stack exchange,提问作者HighTechGamingNL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:56:19