>> dict['key'] [] >>> dict['key'-6ren">
gpt4 book ai didi

python - 如何创建动态字典并向其中添加列表内容

转载 作者:行者123 更新时间:2023-12-02 02:33:45 26 4
gpt4 key购买 nike

我创建了以下逻辑来将列表添加到Python中的字典中,它工作正常

>>> dict ={}
>>> dict ={"key":[]}
>>> dict['key']
[]
>>> dict['key'].append('a')
>>> dict['key']
['a']

当我尝试在解析 JSON 并根据某些情况创建动态字典时实现相同的操作时,它无法添加到列表中并报告为 NoneType

import json
json_data="""{
"data":[
{
"package_path":"/bin/bash",
"package_type":"rpm"
},
{
"package_path":"com.test3",
"package_type":"java"
},
{
"package_path":"com.test",
"package_type":"java"
}
]
}
"""

j_dict = json.loads(json_data)

dict2 = {}
for vuln in j_dict['data']:
package_type = vuln['package_type']
package_path = vuln['package_path']

if package_type in dict2:
dict2 ={package_type:[]}
else:
dict2[package_type].append(package_path)

抛出错误

 % python ~/Desktop/test.py
Traceback (most recent call last):
File "test.py", line 30, in <module>
dict2[package_type].append(package_path)
KeyError: u'rpm'

预期输出如下

dict2 {"java":['com.test3','com.test2'],"rpm":['/bin/bash']}

最佳答案

您可以使用dict.setdefault如果在字典中找不到该键,则创建空列表。例如:

import json
json_data="""{
"data":[
{
"package_path":"/bin/bash",
"package_type":"rpm"
},
{
"package_path":"com.test3",
"package_type":"java"
},
{
"package_path":"com.test",
"package_type":"java"
}
]
}
"""

j_dict = json.loads(json_data)
out = {}
for vuln in j_dict['data']:
out.setdefault(vuln['package_type'], []).append(vuln['package_path'])

print(out)

打印:

{'rpm': ['/bin/bash'], 'java': ['com.test3', 'com.test']}

关于python - 如何创建动态字典并向其中添加列表内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64648061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com