14

I have a list to be used as keys for the dictionary and every value corresponding to the keys is to be initialized to 0.

2
  • 2
    {k: 0 for k in key_list} Commented Sep 19, 2018 at 17:02
  • 2
    Specifically for your case dict.fromkeys([1, 2, 3], 0) would result in {1: 0, 2: 0, 3: 0} Commented Sep 19, 2018 at 17:03

1 Answer 1

37

You can do with dict.fromkeys

In [34]: dict.fromkeys(range(5),0)
Out[34]: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}
In [35]: dict.fromkeys(['a','b','c'],0)
Out[35]: {'a': 0, 'b': 0, 'c': 0}
Sign up to request clarification or add additional context in comments.

2 Comments

This helps. However what about a list of words as keys?
@NaveedUnjum It will work for the list of words too. Basically it will work for all kind of iterator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.