从字典python中的列表中选择值

时间:2016-04-26 00:28:26

标签: list python-3.x dictionary

我一直在为一个小型联系人导入器工作,现在我正在尝试实现一个块,该块根据要导入的联系人数量自动选择输出文件格式。

但是,每次都会导致错误:

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 个答案:

答案 0 :(得分:1)

主要问题是,当用户键入"q"时,您的代码会离开while循环 name保持&#34; q&#34;作为价值。所以你应该删除这个无用的行:

keyValue = person_dict [name]

由于词典中没有键"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)