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.
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)
).
You want a defaultdict
so you don't need to initialize the sets in the first place:
>>> from collections import defaultdict
>>> d = defaultdict(set)
# That's it, initialization complete. Use goes like this:
>>> d[1].add('a')
>>> d[2].add('b')
>>> d[3].add('c')
>>> d
defaultdict(<class 'set'>, {1: {'a'}, 2: {'b'}, 3: {'c'}})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.