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(somelist, [1 for i in somelist]))
it does work but not sure if it's the most efficient or pythonic way to do it
Any other ways to do it, preferably the simplest way?
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
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