Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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):
    print(findContactsByName(name))
    if inp == 3:
        print("Item 3 was selected: Find contact")
        name = input("Enter name of contact to find: ")
        displayContactsByName(name)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']}")
        print()

result=findContactsByName("joe")
printResult(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading