pythonlistdictionary

In Python: Create a dictionary from a list of keys, but set all values to 0?


I've found elegant solutions to create dictionaries from two lists:

keys = [a, b, c]
values = [1, 2, 3]
list_dict = {k:v for k,v in zip(keys, values)}

But I haven't been able to write something for a list of keys with a single value (0) for each key. I've tried to do something like:

list_dict = {k:v for k,v in (zip(keys,[0 for i in range(keys)]))}

But it should be possible with syntax something simple like:

dict_totals = {k:v for k,v in zip(keys,range(0,3))}

I'm hoping for output that looks like {a:0, b:0, c:0}. Am I missing something obvious?


Solution

  • Using dict.fromkeys alternate initializer:

    dict.fromkeys(keys, 0)
    

    And offering you an easier way to do the first one:

    dict(zip(keys, values))