什么是一个字典的好搜索功能

问题描述:

我一直在使用这个,但似乎并不适用于每次添加第二个条目后进行搜索的多个条目,如果我尝试搜索第一个入口就是第二个入口。这将是一个修复什么是一个字典的好搜索功能

 for i in range(len(gclients)): 
      record = gclients[i] 
      if record["Name"].lower() == search1: 
       if record["Surname"].lower() == search2: 
        recordfoundc = True 


      for k,v in record.iteritems(): 
       resname = record["Name"] 
       resSurname = record["Surname"] 
       resnum = record["Phone Number"] 
       resjob = record["Job"] 
       resaddress = record["Address"] 
       resemID = record["Employee ID"] 

     if recordfoundc: 
      print"You have just found",resname,resSurname,resnum,resjob, resaddress, resemID 
      recordfoundc = False 

     else: 
      print "Client not found" 
+3

问题寻求帮助调试(“?为什么不是这个代码工作”)必须包括所期望的行为,一个特定的问题或错误,并在最短的代码要重现它在问题本身。没有明确问题陈述的问题对其他读者无益。请参阅:[如何创建最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。 – jurgemaister

+0

移动'for k,v in record.iteritems():'代码在if循环内(在'recordfoundc = True'后面),因为当找到用户细节时只有你必须定义这个变量。也使用'break'语句。 –

+0

请在'gclients:'中用'for record in gclients替换'in range(len(gclients)):record = gclients [i] :-) – mkrieger1

相关代码:

移动for k,v in record.iteritems(): for循环代码中if looprecordfoundc = True之后),因为当员工发现,那么只有你必须得到来自records员工详细信息。

无需for k,v in record.iteritems():声明的,因为我们直接访问从记录键和值,我们没有使用可变k并在代码v

还用break声明。

代码看起来喜欢 - :

recordfoundc = False 
for i in range(len(gclients)): 
    record = gclients[i] 
    if record["Name"].lower() == search1 and record["Surname"].lower() == search2: 
     recordfoundc = True 
     #- Get Details of Employee. 
     resname = record["Name"] 
     resSurname = record["Surname"] 
     resnum = record["Phone Number"] 
     resjob = record["Job"] 
     resaddress = record["Address"] 
     resemID = record["Employee ID"] 

     break 

if recordfoundc: 
    print"You have just found",resname,resSurname,resnum,resjob, resaddress, resemID 
else: 
    print "Client not found" 

的Python允许写多重条件如果循环andor关键字。

演示:

>>> a = 1 
>>> b = 2 
>>> c = 3 
>>> if a==1 and b==2 and c==3: 
... print "In if loop" 
... 
In if loop 
>>> 

Break语句

使用break语句从任何退出的同时,当任何条件得到满足。

在我们的情况下,员工的名字和姓氏在记录中匹配时,不需要检查其他记录项目。

演示:打破for loop当价值i3

>>> for i in range(5): 
... print i 
... if i==3: 
...  print "Break for loop." 
...  break 
... 
0 
1 
2 
3 
Break for loop. 

如何从字典中获得价值。

演示:

>>> record = {"name": "test", "surname":"test2", "phone":"1234567890", "Job":"Developing"} 
>>> record["name"] 
'test' 
>>> record["surname"] 
'test2' 
>>> record["Job"] 
'Developing' 
>>> 
+0

谢谢,这有助于很多,因为你可以告诉我仍然需要学习一些东西 – Mic

+0

@Mic:欢迎PLZ再次看到我更新了答案。免费问我在stackoverflow和我的问题(电子邮件[email protected]) –

+0

好吧,再次感谢我会如果我需要帮助 – Mic

您完成后,您的打印件发生在for循环因此您的结果变量只是你写的最后的(而这些仅需要被写入该记录是否匹配,如尖在评论中)。您需要在for内部打印或将结果添加到列表中以便以后打印。和/或如建议的那样,如果你只想要第一场比赛,就从循环中解脱出来。