Search code examples
pythontinydb

How to extract single field from Tiny DB search


I populate my db, then make a search, I can print the results but I want extract the fields to populate labels or entries, how can I do it ? This is my code

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

Solution

  • You can get list of any field like this

    def getFieldData(fieldName):
        result = [r[fieldName] for r in db]
        return result
    
    print(getFieldData('NAME'))
    print(getFieldData('SURNAME'))