How do I create a dictionary with keys from a list and values defaulting to (say) zero?

blahster picture blahster · Oct 6, 2010 · Viewed 194.4k times · Source

I have a = [1,2,3,4] and I want d = {1:0, 2:0, 3:0, 4:0}

d = dict(zip(q,[0 for x in range(0,len(q))]))

works but is ugly. What's a cleaner way?

Answer

Tim McNamara picture Tim McNamara · Oct 6, 2010

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