如何从JSON中的字典列表中删除字典

时间:2015-06-24 21:32:56

标签: python json dictionary

我将联系人存储在JSON文件中的词典列表中。我希望能够通过用户输入删除联系人。我该怎么做呢?我尝试使用for循环和弹出,但这不起作用。

# Import Collections to use Ordered Dictionary
import collections

# Module used to save contacts to database
import json

# The main class
def main():

    # Creates an empty list of contacts
    contacts = []

    loop = True

    # Create a while loop for the menu that keeps looping for user input until loop = 0
    while loop == True:

        # Prints menu for the user in command line
        print """
        Contact Book App
        a) New Contact
        b) List Contacts
        c) Search Contacts
        d) Delete Contact
        e) Quit
         """

        # Asks for users input from a-e
        userInput = raw_input("Please select an option: ").lower()

        # OPTION 1 : ADD NEW CONTACT
        if userInput == "a":
            contact = collections.OrderedDict()

            contact['name'] = raw_input("Enter name: ").title()
            contact['phone'] = raw_input("Enter phone: ")
            contact['email'] = raw_input("Enter email: ")

            contacts.append(contact)
            json.dump(contacts, open('contacts.json','w'))

            print "Contact Added!"
            # For Debugging Purposes
            # print(contacts)

        # OPTION 2 : LIST ALL CONTACTS
        elif userInput == "b":
            print "Listing Contacts"
            try:
                contacts = json.load(open('contacts.json','r'))
            except:
                contacts = []

            print "%-30s %-30s %-30s" % ('NAME','PHONE','EMAIL')
            for i in contacts:
                print "%-30s %-30s %-30s" % (i['name'], i['phone'], i['email'])

        # OPTION 3 : SEARCH CONTACTS
        elif userInput == "c":
            print "Searching Contacts"
            search = raw_input("Please enter name: ")
            # Want to be able to search contacts by name, phone number or email
            try:
                contacts = json.load(open('contacts.json','r'))
            except:
                contacts = []

            for i in contacts:
                if i['name'] == search:
                    print i['name'], i['phone'], i['email']
                elif i['phone'] == search:
                    print i['name'], i['phone'], i['email']
                elif i['email'] == search:
                    print i['name'], i['phone'], i['email']
                else:
                    print "No Such Contact"

        # OPTION 4 : DELETE A CONTACT
        elif userInput == "d":
            print "Deleting Contact"
            deleteQuery = raw_input("Enter Contact Name: ")
            obj = json.load(open('contacts.json'))

            for i in contacts(len(obj)):
                if obj[i]['name'] == deleteQuery:
                    obj.pop(i)


        # OPTION 5 : QUIT PROGRAM
        elif userInput == "e":
            print "Quitting Contact Book"
            loop = False
        else:
            print "Invalid Input! Try again."


main()

2 个答案:

答案 0 :(得分:1)

你走在正确的轨道上,流行音乐应该有效。我修改了你的代码,以便'contacts'是一个字典而不是一个列表。然后记录看起来像:

contacts = {'Aname':{'name': name,
                     'phone': phone,
                     'email': email
                     },
            'Bname':{'name': name,
                     'phone': phone,
                     'email': email
                    }
           }

然后,您可以将名称用作包含姓名,电话和电子邮件的嵌套字典对象的键。删除名称现在可以使用contacts.pop(contact_name)。我对代码进行了一些更改以实现此目的。

# Import Collections to use Ordered Dictionary
import collections

# Module used to save contacts to database
import json

# The main class
def main():

    # Creates an empty list of contacts
    contacts = collections.OrderedDict()
    loop = True

    # Create a while loop for the menu that keeps looping for user input until loop = 0
    while loop == True:

        # Prints menu for the user in command line
        print """
        Contact Book App
        a) New Contact
        b) List Contacts
        c) Search Contacts
        d) Delete Contact
        e) Quit
         """

        # Asks for users input from a-e
        userInput = raw_input("Please select an option: ").lower()

        # OPTION 1 : ADD NEW CONTACT
        if userInput == "a":
            contact_name = raw_input("Enter name: ").title()

            contacts[contact_name] = {'name': contact_name,
                                     'phone': raw_input("Enter phone: "),
                                     'email': raw_input("Enter email: ")
                                     }

            json.dump(contacts, open('contacts.json','w'))

            print "Contact Added!"
            # For Debugging Purposes
            # print(contacts)

        # OPTION 2 : LIST ALL CONTACTS
        elif userInput == "b":
            print "Listing Contacts"
            try:
                contacts = json.load(open('contacts.json','r'))
                name_keys = list(contacts.keys())
            except:
                contacts = {}

            print "%-30s %-30s %-30s" % ('NAME','PHONE','EMAIL')

            for k in name_keys:
                print "%-30s %-30s %-30s" % (contacts[k]['name'], contacts[k]['phone'], contacts[k]['email'])

        # OPTION 3 : SEARCH CONTACTS
        elif userInput == "c":
            print "Searching Contacts"
            search = raw_input("Please enter name: ")
            # Want to be able to search contacts by name, phone number or email
            try:
                contacts = json.load(open('contacts.json','r'))
            except:
                contacts = []

            try:
                print "%-30s %-30s %-30s" % (contacts[search]['name'], contacts[search]['phone'], contacts[search]['email'])
            except KeyError:
                print "Not Found"

        # OPTION 4 : DELETE A CONTACT
        elif userInput == "d":
            print "Deleting Contact"
            contact_name = raw_input("Enter Contact Name: ")
            contacts = json.loads(open('contacts.json').read())

            try:
                contacts.pop(contact_name)
                json.dump(contacts, open('contacts.json','w'))
            except KeyError:
                print "Contact Not Found"


        # OPTION 5 : QUIT PROGRAM
        elif userInput == "e":
            print "Quitting Contact Book"
            loop = False
        else:
            print "Invalid Input! Try again."


main()

答案 1 :(得分:0)

python for循环语法指定它通过可迭代。 len返回一个不可迭代的整数。这就是为什么它没有删除;它实际上并没有通过for循环。要解决此问题,请使用range函数创建一个可迭代范围,以便遍历列表:

for i in range(len(obj)):
    #etc