I tried using dict.fromkeys([1,2,3],set()). This initializes creates the dictionary but when I add a value to any one of the sets all the sets get updated!
>>> d=dict.fromkeys([1,2,3],set())
>>> d
>>> {1: set(), 2: set(), 3: set()}
>>> d[1].add('a')
>>> d
>>> {1: {'a'}, 2: {'a'}, 3: {'a'}}
It seems that all the three values of the dictionary are referring to the same set. I want to initialize all the values of the dictionary to empty sets so that I can perform some operations on these sets in a loop based on the keys later.
Using dictionary comprehension
d = {x: set() for x in [1, 2, 3]}
Or using collections.defaultdict
You can use collections.defaultdict
>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> d[1].add('a')
>>> d
defaultdict(<class 'set'>, {1: {'a'}})
>>> d[2].add('b')
>>> d
defaultdict(<class 'set'>, {1: {'a'}, 2: {'b'}})
The way it works, is, when you try to add a value to a key like dict[key].add(value), it checks whether the key is present; if so, then it adds the value to the set. If it is not present the value is added as a set since the default is set as a set (defaultdict(set)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With