Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dictionary with keys from a list and values defaulting to (say) zero? [duplicate]

People also ask

How do you create a dictionary with keys and no values?

In Python to create an empty dictionary with keys, we can use the combination of zip() and len() method. This method will initialize a dictionary of keys and returns no values in the dictionary.

How do you create a dictionary from a list of keys and values?

Using zip() with dict() function The simplest and most elegant way to build a dictionary from a list of keys and values is to use the zip() function with a dictionary constructor.

Can you turn a list into a dictionary?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.


dict((el,0) for el in a) will work well.

Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}.


d = dict.fromkeys(a, 0)

a is the list, 0 is the default value. Pay attention not to set the default value to some mutable object (i.e. list or dict), because it will be one object used as value for every key in the dictionary (check here for a solution for this case). Numbers/strings are safe.


In python version >= 2.7 and in python 3:

d = {el:0 for el in a}

In addition to Tim's answer, which is very appropriate to your specific example, it's worth mentioning collections.defaultdict, which lets you do stuff like this:

>>> d = defaultdict(int)
>>> d[0] += 1
>>> d
{0: 1}
>>> d[4] += 1
>>> d
{0: 1, 4: 1}

For mapping [1, 2, 3, 4] as in your example, it's a fish out of water. But depending on the reason you asked the question, this may end up being a more appropriate technique.


d = dict([(x,0) for x in a])

**edit Tim's solution is better because it uses generators see the comment to his answer.