views:

108

answers:

4

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  A: 
d = dict([(x,0) for x in a])

**edit Tim's solution is better because it uses generators see the comment to his answer.

GWW
+11  A: 

dict((el,0) for el in a)

Tim McNamara
Generator expressions avoid the memory overhead of populating the whole list.
Tim McNamara
+1 for you. I learned something new today.
GWW
@Tim You should probably promote that comment into your actual answer. Also, from Python 2.7 and Python 3 you can do `{el:0 for el in a}`. (Feel free to add that into your answer as well.)
Zooba
Thanks Tim, that's neat
blahster
+2  A: 

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.

intuited
+4  A: 
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. Numbers/strings are safe.

eumiro
the only pythonic way.
SilentGhost
This appears to be cleaner (for me at least), how does it compare to Tim's?
blahster
Tim's solution works for any default values (you can initialize the dictionary with an empty list or datetime object or anything). In my solution, you can initialize it only with immutable objects (int/float, string,...). It is more pythonic for your case (default value is 0) and very probably it is also faster.
eumiro