Is there a way to set all dictionary values ​​to zero?

For example, I have a list of ASCII characters and you want to zip them with a list of zeros equal to the number of characters in the ASCII list,

as:

import string a = string.printable #Gives all ASCII characters as a list ^ b = zeroes * len(a) c = zip(a,b) 

Something like that?

+4
source share
5 answers

You can use dict comprehension:

 { x:0 for x in string.printable} 
+10
source

There is a standard method for this:

 mydict = dict.fromkeys(string.printable, 0) 

or, if you need a list of tuples (to be honest, the Martijn version is more python, but only for a change):

 import itertools tuples = zip(string.printable, itertools.repeat(0)) 
+8
source

Just use a list comprehension:

 c = [(i, 0) for i in a] 
+2
source

This may not help you, but if you are going to use a dictionary to count, you can use defaultdict .

 from collections import defaultdict my_dict = defaultdict(int) 

By default, any key is used.

 >>> print my_dict['a'] 0 
+1
source

Maybe something like this if you need a list:

 import string c = zip(string.printable, [0]*len(string.printable)) 
0
source

Source: https://habr.com/ru/post/1447682/


All Articles