[Python] How to create a dictionary from a list of keys, but set all values to 0?

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página