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?
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?
d = dict([(x,0) for x in a])
**edit Tim's solution is better because it uses generators see the comment to his answer.
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.
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.