Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a dictionary with a list of keys and values as empty sets in python3.6?

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.

like image 440
Zanylytical Scientist Avatar asked Oct 27 '25 13:10

Zanylytical Scientist


2 Answers

Using dictionary comprehension

d = {x: set() for x in [1, 2, 3]}

Or using collections.defaultdict

like image 166
Ignacio Vazquez-Abrams Avatar answered Oct 29 '25 01:10

Ignacio Vazquez-Abrams


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)).

like image 41
Keyur Potdar Avatar answered Oct 29 '25 02:10

Keyur Potdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!