我在附加現有詞典的值時遇到問題。目標是打開一個 json 文件,分析現有的字典,查看是否存在任何服務,如果該服務存在,則附加新密碼。#!/usr/bin/env python3import jsonimport random#a set of characters to chose from for the passwordschar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()\{\}[]-_=+/?.>,<|`~'services = []passlength = 0b = 0#this function takes your input on what services you want in your list of dictionariesdef service_add(): serviceques = input('what service is the password for? ') service = (serviceques) if service == 'done': starter() elif service == '': print('you must enter a service name') service_add() elif service == ' ': print('you must enter a service name') service_add() else: if service in services: print('service and key already exists') else: services.append(service) #print(services) service_add()#function to tell how long you want your password to bedef starter(): lengths = input('How long do you want the password to be? ') global length length = int(lengths) makingPairs()#this function creates a password and puts the password in a dictionary with each #service in your list then appends the set of service and password to a json filedef makingPairs(): global b global services global length a = 0 jsondics= [] for line in services: a = a + 1 for x in range(a): password = '' for c in range(length): password += random.choice(char) jsonpairs = { 'Service' : services[b], 'Password' : password }這是來自 json 文件的原始數據[{"Service": "spotify", "Password": "5QF50W,!UG"}, {"Service": "pandora", "Password": "E=b]|6]-HJ"}]當我運行代碼并嘗試刪除“潘多拉”時,它給了我這個例子[{'Service': 'spotify', 'Password': 'bMXa2FY%Rh'}, {'Password': '$m--c<CY2x'}]問題是,它沒有刪除整個字典,而是只刪除了名為“Pandora”的鍵。我試圖更改new_list變量,但它仍然只刪除鍵或值,而不是整個變量。
1 回答

炎炎設計
TA貢獻1808條經驗 獲得超4個贊
我想你是在問如何根據其中一個鍵的值從字典列表中刪除一個項目。你有:
new_list = [{k: v for k, v in d.items() if v != 'pandora'} for d in JsonDictList]
當你給它這個輸入時:
[{"Service": "spotify", "Password": "5QF50W,!UG"}, {"Service": "pandora", "Password": "E=b]|6]-HJ"}]
"Service": "pandora"
...當您真的希望它刪除整個字典時,它會刪除鍵/值對{"Service": "pandora", "Password": "E=b]|6]-HJ"}
。您的問題還提到了追加(即在集合末尾添加一些內容),但我不清楚您遇到了什么麻煩。所以我只是在回答如何從字典列表中刪除一個元素。
從具有服務“潘多拉”的列表中刪除字典
所以首先,我們可以這樣做:
new_list = [d for d in JsonDictList if d['Service'] != 'pandora']
當它有一個名為“Service”的鍵與一個值“pandora”配對時,它會從列表中刪除每個元素。它還假設每個元素都有一個名為“Service”的鍵,如果其中一個沒有,則會導致異常。如果其中一些可能沒有“服務”密鑰,您可以改為執行以下操作:
new_list = [d for d in JsonDictList if d.get('Service') != 'pandora']
從列表中刪除在任何領域都有“潘多拉”的字典
您的示例還將刪除等于“pandora”的密碼。我認為這不是故意的。但是如果你確實想刪除任何以 'pandora' 作為其任何值的字典,你可以這樣做:
new_list = [d for d in JsonDictList if not any(v == 'pandora' for v in d.values())]
添加回答
舉報
0/150
提交
取消