I have a dictionary where key is string and value is list.
Now while adding a value associated with given key, I always have to check if there is any list yet, otherwise
You can use dict.setdefault:
dict.setdefault
>>> d = {} >>> d.setdefault('k', []).append(1) >>> d {'k': [1]} >>> d.setdefault('k', []).append(2) >>> d {'k': [1, 2]}
Help on method_descriptor in dict: dict.setdefault = setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
Help on method_descriptor in dict:
dict.setdefault = setdefault(...) D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D