Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way I can initialize dictionary values to 0 in python taking keys from a list? [duplicate]

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.

like image 365
kramer Avatar asked Sep 19 '18 17:09

kramer


People also ask

How do you initialize a dictionary to zero?

How do you initialize a dictionary key? If you want to initialize all keys in the dictionary with some default value, you can use the fromkeys() function. If no default value is specified, the dictionary is initialized with all values as None .

What will happen if a dictionary has duplicate keys Python?

Dictionaries in Python However, there are a couple restrictions that dictionary keys must abide by. First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.

How do you remove duplicates from a key-value pair in Python?

You can remove duplicates using a Python set or the dict. fromkeys() method. The dict. fromkeys() method converts a list into a dictionary.

Does dictionary allow duplicates values in Python?

Dictionary. Dictionaries are used to store data values in key:value pairs. A dictionary is a collection which is ordered*, changeable and do not allow duplicates.


1 Answers

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}
like image 140
Rahul K P Avatar answered Sep 18 '22 12:09

Rahul K P