Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to convert a list to a dictionary in Python with keys but no values?

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?

like image 936
PyNEwbie Avatar asked Jun 20 '09 01:06

PyNEwbie


People also ask

Which is more efficient list or dictionary Python?

Therefore, the dictionary is faster than a list in Python. It is more efficient to use dictionaries for the lookup of elements as it is faster than a list and takes less time to traverse. Moreover, lists keep the order of the elements while dictionary does not.

Can a list be convert into a dictionary Python?

You can convert a Python list to a dictionary using the dict. fromkeys() method, a dictionary comprehension, or the zip() method. The zip() method is useful if you want to merge two lists into a dictionary.

What are the advantages of dictionary over list in Python?

It is more efficient to use a dictionary for lookup of elements because it takes less time to traverse in the dictionary than a list. For example, let's consider a data set with 5000000 elements in a machine learning model that relies on the speed of retrieval of data.

Which is faster list tuple or dictionary?

It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.


2 Answers

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.

like image 51
Ayman Hourieh Avatar answered Oct 05 '22 04:10

Ayman Hourieh


You could use a set instead of a dict:

>>> myList=['a','b','c','d']
>>> set(myList)
set(['a', 'c', 'b', 'd'])

This is better if you never need to store values, and are just storing an unordered collection of unique items.

like image 26
Greg Hewgill Avatar answered Oct 05 '22 03:10

Greg Hewgill