Nov-03-2020, 05:58 AM
(This post was last modified: Nov-03-2020, 12:50 PM by naughtysensei.)
so what I wanna do is this but something cleaner(short):
What I really wanted was to run a loop and add values (to the set) for the corresponding keys if it(key) exists, and if not create one(key with an empty set) and add then.
In an another attempt one could create dictionary beforehand with all values being empty sets. then just add to the value(to the set) without using if-else:
But this would be an issue if I don't know what the keys would be. Again I wanna do this in a loop for multiple keys & values. This is just a simpler version of my problem.
EDIT: did some searching this should be it.
EDIT0: collections.defaultdict is perfect
1 2 3 4 5 6 |
dic = {} if key0 not in dic.keys(): dic[key0] = set () dic[key0].add( 2 ) else : dic[key0].add( 2 ) |
In an another attempt one could create dictionary beforehand with all values being empty sets. then just add to the value(to the set) without using if-else:
1 2 |
dic = {key0: set (), key1: set (), key2: set ()} dic[key0].add( 2 ) |
EDIT: did some searching this should be it.
1 2 |
dic.setdefault(key0, set ()) dic[key0].add( 2 ) |