Search code examples
pythonnosqlin-memory-databaseunqlite

How to extract a field value from UnQLite collection


db = UnQLite('test.db')
data = db.collection('data')
print(data.fetch(0))

This prints

{'id': b'abc', 'type': b'business', 'state': b'AZ', 'latitude': 33.3482589, 
 'name': b"ABC Restaurant", 'full_address': b'1835 E ABC Rd, Ste C109, Phoenix, AZ 85284',
 'categories': [b'Restaurants', b'Buffets', b'Italian'],
 'open': True, 'stars': 4, 'city': b'Phoenix', 'neighborhoods': [], 
 '__id': 0, 'review_count': 122, 'longitude': -111.9088346}

How do I fetch the value "Phoenix" for City?

type(data.fetch(0)) prints class 'dict'

I am looking at UnQlite documentation, not finding much. Please help.


Solution

  • You already get a dict so you only need to search for the key

    x = {'id': b'abc', 'type': b'business', 'state': b'AZ', 'latitude': 33.3482589, 
     'name': b"ABC Restaurant", 'full_address': b'1835 E ABC Rd, Ste C109, Phoenix, AZ 85284',
     'categories': [b'Restaurants', b'Buffets', b'Italian'],
     'open': True, 'stars': 4, 'city': b'Phoenix', 'neighborhoods': [], 
     '__id': 0, 'review_count': 122, 'longitude': -111.9088346}
    x['city']
    #b'Phoenix'
    

    Here Phoenix is not a str object but byte so if you want it as string you can convert it by using decode

    x['city'].decode()
    #'Phoenix'
    

    Or in your case:

    data.fetch(0)['city'].decode()