'Simple way to convert list into dict with False values [duplicate]
What is the simplest way to convert some list like
l = ['a', 'b', 'c']
...into a dict of following form:
d = {'a': False, 'b': False, 'c': False}
Solution 1:[1]
As enke suggested you can use fromkeys method of dict class to convert the list or any other iterable into a dict by a fixed value for all keys.
In [1]: a = [1,2, "hello"]
In [2]: dict.fromkeys(a, False)
Out[2]: {1: False, 2: False, 'hello': False}
And also you can use dict comprehension as below:
In [1]: a = [1,2, "hello"]
In [2]: {key: False for key in a}
Out[2]: {1: False, 2: False, 'hello': False}
Solution 2:[2]
Solution 3:[3]
You can use dict-comprehension, Pythonic-style:
>>> l = ['a', 'b', 'c']
>>> dct = {x: False for x in l}
>>> dct
{'a': False, 'b': False, 'c': False}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | richardec |
| Solution 2 | Pac0 |
| Solution 3 | richardec |
