Python Converting A List Into A Dict With A Value Of 1 For Each Key
I have: somelist = ['a', 'b', 'c', 'd'] I want it so that, the list would convert to a dict somedict = {'a' : 1, 'b' : 1, 'c' : 1, 'd' : 1} So I did: somedict = dict(zip(somelis
Solution 1:
You can just use fromkeys()
for this:
somelist = ['a', 'b', 'c', 'd']
somedict = dict.fromkeys(somelist, 1)
You can also use a dictionary comprehension (thanks to Steven Rumbalski for reminding me)
somedict = {x: 1 for x in somelist}
fromkeys
is slightly more efficient though, as shown here.
>>>timeit('{a: 1 for a in range(100)}')
6.992431184339719
>>>timeit('dict.fromkeys(range(100), 1)')
5.276147376280434
Post a Comment for "Python Converting A List Into A Dict With A Value Of 1 For Each Key"