Python Forum
Searching for nested items within the dictionary data structure
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching for nested items within the dictionary data structure
#1
I've been studying the dictionary data structure as I wanted to discover a way of searching for nested items, so this code is a demonstration of that goal; I understand that it's possibly over engineered for the task that I have chosen.

The user input is not fully sanitized, but (as you will see from the code comments) I have that covered by a custom function that I've already written (for the sake of brevity, that function is not included here).

Also, (for the sake of brevity) I've only included a few books, but you can add as many as you like, for testing.

I know not of any bugs, so if you find any or if you have any general comments about my coding style, I'm open to constructive criticism.

Thank you reading and testing; I'll reply to any comments you may have, as and when.

Enjoy and who knows, you may even find this to be the bases of a useful app.

#!/usr/bin/python3

from sys import stdout

library = { # list indexed as 0 for the book title and 1 for the book author
        'computer science & programming':{
            '0-13-110163-3':[
                'THE C PROGRAMMING LANGUAGE',
                'BRIAN W.KERNIGHAN & DENNIS M.RITCHIE'
                ],
            '0-85934-229-8':[
                'PROGRAMMING IN QuickBASIC',
                'N.KANTARIS'
                ],
            '0-948517-48-4':[
                'HiSoft BASIC VERSION 2: USER MANUAL',
                'DAVID NUTKINS, ALEX KIERNAN and TONY KENDLE'
                ]
            },
        'reference':{
            '0-333-34806-0':[
                'DICTIONARY OF INFORMATION TECHNOLOGY',
                'DENNIS LONGLEY and MICHAEL SHAIN'
                ]
            },
        'novels':{
            '0-681-40322-5':[
                'THE MORE THAN COMPLETE HITCHHIKER\'S GUIDE',
                'DOUGLAS ADAMS'
                ]
            }
    }
#===========<End of dictionary>===========#
def search(publication, term):
    result = []
    results = []
    found = 0
    maximum = 6
    title = 0
    author = 1
    categories = library.keys()
    for category in library:
        for isbn in library[category]:
            book = library.get(category).get(isbn)
            if term[:4] == 'ISBN' and term[4:] == isbn:
                term = book[title]
            if term in book[publication]:
                found += 1
                result.append(book[title])
                result.append(book[author])
                result.append(category)
                result.append(isbn)
                results.append(result)
                result = []
                if found > maximum:
                    break
        if found > maximum:
            break
    if found:
        if found > maximum:
            return maximum
        else:
            return results
    else:
        return
#=========<End of search function>=========#
def output(results, file=stdout):
    print("-"*50)
    if isinstance(results, list):
        for books in results:
            for book in books:
                print(book)
            print("-"*50)
    else:
        print("Search results exceeds the maximum of {}".format(results))
        print("-"*50)
#=========<End of output function>=========#
find, found = None, None
 
# attempt = the index reference passed to <if term in book[publication]>
attempt = 0 # 0 = book title 1 = book author

quit = False
while not find and not quit:
    print('''
Search term must be alphanumeric characters only
and greater than three characters in length.

For a ISBN search, enter ISBN and press return.
    ''')
    find = input("Search term: ").strip().upper() # to-do: check the input with the user input checker function
    if find == 'QUIT':
        quit = True
    elif find =='ISBN':
        print("ISBN search")
        isbn = input("ISBN: ").strip()
        find = find+isbn
    if len(find) > 3:
        found = search(attempt, find)
    else:
        find, found = None, None
    if find and not quit:
        while not found and attempt < 1: # change this if more fields are added to the publication
            attempt +=1
            found = search(attempt, find)
    if found:
        output(found)
        find, found = None, None
        attempt = 0
    elif not quit:
        print("Nothing found")
        find = None
        attempt = 0

print("Search exit.")
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Messages In This Thread
Searching for nested items within the dictionary data structure - by rob101 - Aug-30-2022, 08:55 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020