Python – trying to understand searching through nested dictionaries

trying to understand searching through nested dictionaries… here is a solution to the problem.

trying to understand searching through nested dictionaries

I have a list of contact information stored in nested dicts:

addressBook = {'Jim': {'name': 'James Marsh', 'address': '32 Morris Ave',
                           'phone': '654-987-3217'},
    'Leanne': {'name': 'Leanne Moss', 'address': '37 Shamrock Lane',
                           'phone': '123-456-7890'},
    'Chris': {'name': 'Christopher Philips', 'address': '49 Langley Court',
                           'phone': '321-654-9870'},
'Tim': {'name': 'Timothy Morris', 'address': '49 Langley Court',
                       'phone': '321-654-9870'}}

I’m trying to write a function that will search for the search string entered by the user in each entry.

def searchAllFields(addressBook):
    searchString = input("Enter a string to search for (enter to cancel): ")
    if searchString == "":
        return
    else:
        for key, value in addressBook.items():
            inside = False
            for v in value.values():
                if searchString in v:
                    inside = True
                    break
            if searchString in key or inside:
                print("The following contacts were found: ")
                print(addressBook[key]['name'])
                print(addressBook[key]['address'])
                print(addressBook[key]['phone'] + '\n')
            else:
                print("No contact matching the string {} was found.". format(searchString))
                return

My function iterates through the dictionary nicely, but it only finds the search string in the key. For example, if I search for a string in Jim, I can find James’ information, but if my search string is Lang, I want to be able to find Chris. I thought for key, value in addressBook.items(): would look at the value and key. Why not? How do I fix this?

Solution

When you execute searchString in value, you are only checking the key of that value dictionary.

You need a second loop to check the values of nested dictionaries

for key, value in addressBook.items():
    inside = False
    for v in value.values():
        if searchString in v:
            inside = True 
            break
    if searchString in key or inside:

Irrelevant: searchString in key is checking substrings, not exact matches

Related Problems and Solutions