Is there a better way to convert a list to a dictionary in Python with keys but no values?
dictionary, list, list-comprehension, python
Solution
Use `dict.fromkeys`:
>>> my_list = [1, 2, 3]
>>> dict.fromkeys(my_list)
{1: None, 2: None, 3: None}
Values default to `None`, but you can specify them as an optional argument:
>>> my_list = [1, 2, 3]
>>> dict.fromkeys(my_list, 0)
{1: 0, 2: 0, 3: 0}
From the docs:
a.fromkeys(seq[, value]) Creates a new dictionary with keys from seq and values set to value.
dict.fromkeys is a class method that returns a new dictionary. value defaults to None. New in version 2.3.
Problem
I was sure that there would be a one liner to convert a list to a dictionary where the items in the list were keys and the dictionary had no values. The only way I could find to do it was argued against. "Using list comprehensions when the result is ignored is misleading and inefficient. A `for` loop is better" ``` myList = ['a','b','c','d'] myDict = {} x=[myDict.update({item:None}) for item in myList] >>> myDict {'a': None, 'c': None, 'b': None, 'd': None} ``` It works, but is there a better way to do this?