Home > Software engineering >  dictionary append another dictionary to specific key
dictionary append another dictionary to specific key

Time:12-16

i have a dictionary I would like to append to another dictionary's HIGHSEVERITY key to.

vulnsBySeverity={"HIGHSEVERITY":"", "MEDIUMSEVERITY":"", "LOWSEVERITY":""}
for result in json_object['results']:
    for vuln in result['vulnerabilities']:
        if vuln["severity"] == "high":
            print("Its high!: {}".format(vuln))
            vulnsBySeverity["HIGHSEVERITY"].update(vuln)

However, when I run this last line it gives me an error of:

AttributeError: 'str' object has no attribute 'update'

What im looking to do is append the value of vuln (a dictionary) to the dictionary key vulnsBySeverity["HIGHSEVERITY"] but getting that error? Note this dictionary vulnsBySeverity will have more than 1 vuln that im attempting to append to the HIGHSEVERITY key.

Can someone help me out? Please, and thank you.

CodePudding user response:

The .update() method is applicable to a dict, but vulnsBySeverity["HIGHSEVERITY"] is a string (from the initialization)

In your case, you don't need this method i think. A simple = should do the trick:

vulnsBySeverity["HIGHSEVERITY"] = vuln

If multiple vuln may have a "high" priority, you could think of using a list too:

vulnsBySeverity["HIGHSEVERITY"] = []

for result in json_object['results']:
    for vuln in result['vulnerabilities']:
        if vuln["severity"] == "high":
            vulnsBySeverity["HIGHSEVERITY"].append(vuln)

Take care of mutability in these cases, if you're modifying vuln after the assignments. (Use vuln.copy() in this case)

Note: As mentionned in your comments, you can initialize vulnsBySeverity["HIGHSEVERITY"] to use .update() but this won't work if multiple vuln have a "high" priority (Only the last one will be taken into account. Previous ones will be overwritten because of the update)

Note: You can use list comprehension too, if you use the list solution:

for result in json_object['results']:
    vulnsBySeverity["HIGHSEVERITY"] = [vuln for vuln in result['vulnerabilities'] if vuln["severity"] == "high"]

CodePudding user response:

The problem is the value of the dictionary vulnsBySeverity is an empty string. string type has no update method. I think a dictionary of lists would be better. And append the vuln dictionaries to the list like below.

vulnsBySeverity = {"HIGHSEVERITY": [], "MEDIUMSEVERITY": [], "LOWSEVERITY": []}

for result in json_object['results']:
    for vuln in result['vulnerabilities']:
        if vuln["severity"] == "high":
            print("Its high!: {}".format(vuln))
            vulnsBySeverity["HIGHSEVERITY"].append(vuln)
  • Related