I have a list to be used as keys for the dictionary and every value corresponding to the keys is to be initialized to 0.
Asked
Active
Viewed 3.6k times
13
-
2`{k: 0 for k in key_list}` – user2390182 Sep 19 '18 at 17:02
-
2Specifically for your case `dict.fromkeys([1, 2, 3], 0)` would result in `{1: 0, 2: 0, 3: 0}` – Patrick Haugh Sep 19 '18 at 17:03
1 Answers
35
You can do with dict.fromkeys
In [34]: dict.fromkeys(range(5),0)
Out[34]: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
In [35]: dict.fromkeys(['a','b','c'],0)
Out[35]: {'a': 0, 'b': 0, 'c': 0}

Rahul K P
- 15,740
- 4
- 35
- 52
-
2
-
@NaveedUnjum It will work for the list of words too. Basically it will work for all kind of iterator. – Rahul K P Sep 19 '18 at 17:18