5

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?

0

1 Answer 1

12

Using dict.fromkeys alternate initializer:

dict.fromkeys(keys, 0)

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

dict(zip(keys, values))
Sign up to request clarification or add additional context in comments.

1 Comment

…and, if you want to do it using dict comprehension anyway, it is just list_dict = {k:0 for k in keys} - nothing complicated about this…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.