I have created the below logic to add list to a dictionary in Python it works fine
>>> dict ={}
>>> dict ={"key":[]}
>>> dict['key']
[]
>>> dict['key'].append('a')
>>> dict['key']
['a']
When I try to Implement same thing while parsing the JSON and creating dynamic dictionary based on certain it failed to add in the List and report as 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)
Throws error
% 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'
Expecting output like
dict2 {"java":['com.test3','com.test2'],"rpm":['/bin/bash']}