2016-04-26 38 views
1

我一直在研究一个小的联系人导入器,现在我试图实现一个块,它根据要导入的联系人数自动选择输出文件格式。从字典python中的列表中选择值

然而,每次都导致错误:

KeyError: 'q' 

我想不出我的生活为什么发生这种情况,我很想提供任何帮助。

我对可扩展性的想法是,字典personDict的格式是personDict = {nameid:[name,email]},但没有任何效果。

任何帮助是好的帮助,

感谢

def autoFormat(): 
    while True: 
     name = input("Enter the person's name \n") 
     if name == "q": 
      break 
     email = input("Enter the person's email \n") 
     personDict[name] = [name, email] 

    if len(personDict) <= 10: 
     keyValue = personDict[name] 
     for keyValue in personDict: 
      for key, value in personDict.iteritems(): 
       combined = "BEGIN:VCARD\nVERSION:4.0\n" + "FN:" + name + "\n" + "EMAIL:" + email + "\n" + "END:VCARD" 
       fileName = name + ".vcl" 
       people = open(fileName, 'a') 
       people.write(combined) 
       people.close() 
       print("Created file for " + name) 

autoFormat() 

回答

1

的主要问题是,用户类型"q"代码离开while循环 与name保持“Q”的值时。所以,你应该删除这个没用行:

的keyValue = person_dict [名]

因为在你的字典与关键"q"没有元素。

同样在导出部分中,您使用与您循环的文件值不同的文件值编写。 您的密码变为:

if len(personDict) <= 10: 
    for name, email in personDict.values(): 
      combined = "BEGIN:VCARD\nVERSION:4.0\n" + "FN:" + name + "\n" + "EMAIL:" + email + "\n" + "END:VCARD" 
      fileName = name + ".vcl" 
      people = open(fileName, 'a') 
      people.write(combined) 
      people.close() 
      print("Created file for " + name)