【问题标题】:Searching for a specific value within a list of dictionaries在字典列表中搜索特定值
【发布时间】:2023-01-01 21:09:03
【问题描述】:
我需要能够打印字典列表中某个名称的所有实例。我似乎无法以所需的格式打印它们。当它是小写并且名称是大写时,它也不起作用。
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)
当名称“Joe”被放入输出时:
[{'name': 'Joe', 'surname': ' Miceli', 'DOB': ' 25/06/2002', 'mobileNo': ' 79444425', 'locality': ' Zabbar'}, {'name': 'Joe', 'surname': 'Bruh', 'DOB': '12/12/2131', 'mobileNo': '77777777', 'locality': 'gozo'}]
当名字“乔”时:
[]
预期输出:
name : Joe
surname : Miceli
DOB : 25/06/2002
mobileNo : 79444425
locality : Zabbar
name : Joe
surname : Bruh
DOB : 12/12/2131
mobileNo : 77777777
locality : gozo
【问题讨论】:
标签:
python
list
csv
dictionary
printing
【解决方案1】:
将第一个函数更改为:
def findContactsByName(name):
return [element for element in contacts if element['name'].lower() == name.lower()]
为了考虑大小写的差异,我只是在比较部分将字典中的名称和输入的名称转换为小写。
为了能够以您指定的格式打印它,您可以创建一个函数,如下所示:
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)
【解决方案2】:
我修改了你的程序。现在您不必担心大小写和输出格式。
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('
')
displayContactsByName('Joe')
【解决方案3】:
大小写问题可以通过将比较的每一侧设置为大写或小写来解决。
return [element for element in contacts if element['name'].upper() == name.upper()]
对于打印语句的格式,您可以使用 json 模块:
import json
print(json.dumps( findContactsByName(name), sort_keys=True, indent=4))