需要为我的字典定义一个“搜索”功能

时间:2019-06-02 12:48:23

标签: python

我需要为我的代码定义一个搜索功能,以在字典中搜索字母。我只缺少实际的“搜索”循环和代码。为了便于阅读,省略了许多代码行。

fileprivate func layout() {
        view.addSubview(profileImage)
        NSLayoutConstraint.activate([
        profileImage.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        profileImage.centerYAnchor.constraint(equalTo: view.centerYAnchor),
        profileImage.heightAnchor.constraint(equalToConstant: 200),
        profileImage.widthAnchor.constraint(equalToConstant: 200),
        ])
}
while True:
  option = get_option()
  ...
  elif (option == "S"):
    search(users)
  ...
users = {}

def add(users):
  student_number = input('Enter student number: ')
  family_name = input("Enter family name: ")
  first_name = input("Enter first name: ")
  phone_number = input('Enter phone number: ')

  single_info = {"student_number": student_number, "family_name": family_name, "first_name": first_name, "phone_number": phone_number}

  users[student_number] = single_info
  print("Record is added.")
...
family_name = input("Enter family name: ")
first_name = input("Enter first name: ")

这是输入字典,我需要一个搜索功能来搜索其中的名称。

预期输出是

#              STN            Name                          Phone          
1              0123456        John Smith                    111222         
2              1111111        Mary Lee                      001122         
3              2222222        Hoa Zhang                     334455 
2              7676767        Milka Sjanovic                012012  

1 个答案:

答案 0 :(得分:1)

您可以使用理解遍历字典以构建结果集:

text = input("Enter text to search:").lower()
result = [ s for s in users.values() if text in (s["family_name"]+" "+s["first_name"]).lower() ]
print(f"Search found {len(result)} records")
for i,s in enumerate(result):
   print(i+1,s["student_number"],s["first_name"],s["family_name"],s["phone_number"])

注意:鉴于您没有提供可用的测试数据,我只在答案框中输入了此数据。您将需要修正所有拼写错误,并自行添加格式

您还可以像这样将条件定义与搜索过程分开:

criteria = lambda s:any(text in s[n].lower() for n in ["family_name","first_name"]) 
result   = list(filter(criteria,users.values())) 

这将为您提供更大的灵活性,并能够轻松地在其他字段上创建搜索。例如,在任何字段中搜索:

criteria = lambda s: text in " ".join(s.values()).lower()
result   = list(filter(criteria,users.values()))