Searching for a specific value within a list of dictionaries

Question:

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 
Asked By: Wild Alex

||

Answers:

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

result=findContactsByName("joe")
printResult(result)
Answered By: Anonymous

I modified your program. Now you don’t have to worry about the case and the output formatting.

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

def findContactsByName(name):
    return [element for element in contacts if element['name'].lower() == name.lower()]
       
def displayContactsByName(name):
    for i in range(len(findContactsByName(name))):
        for j in contacts[i]:
            print('{}: {}'.format(j, contacts[i][j]))
        print('n')
    
displayContactsByName('Joe')

Answered By: Vikash

Case issue can be solved by setting each side of the comparison to UPPERCASE or LOWERCASE.

return [element for element in contacts if element['name'].upper() == name.upper()]

For the format of the print statement you could use the json module:

import json

print(json.dumps( findContactsByName(name), sort_keys=True, indent=4))

Answered By: Sean Conkie