Python Forum

Full Version: create empty sets for keys in a dictionary and add values to the set
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
so what I wanna do is this but something cleaner(short):
dic = {}
if key0 not in dic.keys():
	dic[key0] = set()
	dic[key0].add(2)
else:
	dic[key0].add(2)
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:
dic = {key0: set(), key1: set(), key2: set()}
dic[key0].add(2)
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.
dic.setdefault(key0, set())
dic[key0].add(2)
EDIT0: collections.defaultdict is perfect
collections.defaultdict can help.

from collections import defaultdict

setdict = defaultdict(set)
setdict[42].add(1337)
setdict[0].add("Foo")

print(setdict)