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


Question

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?

1
130
9/28/2013 2:22:57 AM

Accepted Answer

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

193
5/26/2015 10:06:41 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon