[英]How to delete dictionary from list of dictionaries in JSON
我的聯系人存儲在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()
您走在正確的軌道上,流行音樂應該起作用。 我更改了您的代碼,以便“聯系人”是字典而不是列表。 那么記錄可以如下所示:
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()
python for
循環語法指定它經過可迭代。 len
返回一個不可迭代的整數。 這就是為什么它不刪除; 它實際上並沒有通過for循環。 要解決此問題,請使用range
函數創建一個可迭代范圍以如下方式遍歷列表:
for i in range(len(obj)):
#etc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.