如何从 Tiny DB 搜索中提取单个字段

How to extract single field from Tiny DB search

我填充我的数据库,然后进行搜索,我可以打印结果,但我想提取字段来填充标签或条目,我该怎么做? 这是我的代码

from tinydb import TinyDB, Query, where

db = TinyDB('rubrica.json')
def populate():
    Item1 = {'NAME': 'John', 'SURNAME': 'SMITH', 'PHONE': '1234'}
    Item2 = {'NAME': 'Bob', 'SURNAME': 'DEAN', 'PHONE': '5678'}
    Item3 = {'NAME': 'Jack', 'SURNAME': 'DEAN', 'PHONE': '9157'}

    db.insert(Item1)
    db.insert(Item2)
    db.insert(Item3)

def readall():
    for item in db:
        print(item)

def printsearch():
    results =db.search(where('SURNAME') == 'DEAN')
    print(*results, sep='\n')

printsearch()

您可以像这样获取任何字段的列表

def getFieldData(fieldName):
    result = [r[fieldName] for r in db]
    return result

print(getFieldData('NAME'))
print(getFieldData('SURNAME'))

很好的建议,我解决了:

def getFieldData(fieldName):
    results = db.search(where('SURNAME') == 'DEAN')
    result = [r[fieldName] for r in results]
    return result
res = getFieldData('NAME')
for name in res:
    print(name)