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?
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.
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.
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.
It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With