Searching for a specific value within a list of dictionaries

I need to be able to print all instances of a name within the list of dictionaries. I can’t seem to be able to print them in the desired format. It also doesn’t work when it’s in lowercase and the name is in uppercase.

def findContactsByName(name):
    return [element for element in contacts if element['name'] == name]
def displayContactsByName(name):
    if inp == 3:
        print("Item 3 was selected: Find contact")
        name = input("Enter name of contact to find: ")

When the name ‘Joe’ was put in the output is:

[{'name': 'Joe', 'surname': ' Miceli', 'DOB': ' 25/06/2002', 'mobileNo': ' 79444425', 'locality': ' Zabbar'}, {'name': 'Joe', 'surname': 'Bruh', 'DOB': '12/12/2131', 'mobileNo': '77777777', 'locality': 'gozo'}]

When the name ‘joe’:


Expected output:

name :  Joe
surname :   Miceli
DOB :   25/06/2002
mobileNo :   79444425
locality :   Zabbar 

name :  Joe
surname :   Bruh
DOB :   12/12/2131
mobileNo :   77777777
locality :   gozo 

>Solution :

Change the first function to:

def findContactsByName(name):
    return [element for element in contacts if element['name'].lower() == name.lower()]

To account for the differences in uppercase and lowercase, I’ve just converted the name in the dictionary and the entered name to lowercase during the comparison part alone.

To be able to print it in the format that you’ve specified you could make a function for the same as follows:

def printResult(result):
    for d in result:
        print(f"name: {d['name']}")
        print(f"surname: {d['surname']}")
        print(f"DOB: {d['DOB']}")
        print(f"mobileNo: {d['mobileNo']}")
        print(f"locality: {d['locality']}")


Leave a Reply