Home > Net >  Assume you have to add key: list[values] to a dictionary if key does not exist and add to list[value
Assume you have to add key: list[values] to a dictionary if key does not exist and add to list[value

Time:12-14

if key in dict
    dict[key].extend([values*])
else:
    dict[key] = [values*]

//PSEUDOCODE

If it makes any difference, I a using JavaScript and have to store key value pairs in a class dictionary.

CodePudding user response:

if key not in dict:
    dict[key] = []
dict[key].extend(values)

(Though don't use dict as a variable name in python.)

CodePudding user response:

This can be done using a default dictionary.

from collections import defaultdict
def default_value():
    return []

dict = defaultdict(default_value)
dict[key].append(5)

If there is not value for that key when appending, a new key value pair will be created with an empty list as the value.

  • Related