Selecting values from list in dictionary python
Question: I've been working on a small contact importer, and now I'm trying to implement
a block that automatically selects the output file format based on the number
of contacts to be imported.

However, every time it results in the error:

    
    
    KeyError: 'q'
    

I can't figure out for the life of me why this is happening, and I would love
any help offered.

My idea of scalability is that the dictionary `personDict` would be of the
format `personDict = {nameid:[name,email]}`, but nothing works.

Any help is good help,

Thanks

    
    
    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()
    


Answer: The main problem is that when the user types `"q"` your code leaves the
`while` loop with `name` keeping "q" as value. So you should remove this
useless line:

keyValue = person_dict[name]

Since there is no element with key `"q"` in your dictionary.

Also in the export part you write in file values different from those you loop
with. Your code becomes:

    
    
    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)
    

