How do I create a dictionary with keys from a list and values defaulting to (say) zero?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Book End
--
Chapters
00:00 How Do I Create A Dictionary With Keys From A List And Values Defaulting To (Say) Zero?
00:15 Accepted Answer Score 263
00:33 Answer 2 Score 225
00:54 Answer 3 Score 20
01:06 Answer 4 Score 8
01:34 Answer 5 Score 5
01:43 Thank you
--
Full question
https://stackoverflow.com/questions/3869...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary
#avk47
ACCEPTED ANSWER
Score 265
dict((el,0) for el in a) will work well. 
Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}. 
ANSWER 2
Score 226
d = dict.fromkeys(a, 0)
a is the list, 0 is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.
ANSWER 3
Score 8
In addition to Tim's answer, which is very appropriate to your specific example, it's worth mentioning collections.defaultdict, which lets you do stuff like this:
>>> d = defaultdict(int)
>>> d[0] += 1
>>> d
{0: 1}
>>> d[4] += 1
>>> d
{0: 1, 4: 1}
For mapping [1, 2, 3, 4] as in your example, it's a fish out of water.  But depending on the reason you asked the question, this may end up being a more appropriate technique.
ANSWER 4
Score 5
d = dict([(x,0) for x in a])
**edit Tim's solution is better because it uses generators see the comment to his answer.