我在附加现有词典的值时遇到问题。目标是打开一个 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
提交
取消