Python converts a list to dict with a value of 1 for each key

I have:

somelist = ['a', 'b', 'c', 'd']

I want this list converted to dict

somedict = {'a' : 1, 'b' : 1, 'c' : 1, 'd' : 1}

So I did:

somedict = dict(zip(somelist, [1 for i in somelist]))

it works, but not sure if this is the most efficient or pythonic way to do it

Any other ways to do this, preferably the easiest way?

+4
source share
1 answer

You can simply use fromkeys()for this:

somelist = ['a', 'b', 'c', 'd']
somedict = dict.fromkeys(somelist, 1)

You can also use dictionary comprehension (thanks Steven Rumbalski for reminding me)

somedict = {x: 1 for x in somelist}

fromkeys slightly more efficient as shown here.

>>> timeit('{a: 1 for a in range(100)}')
6.992431184339719
>>> timeit('dict.fromkeys(range(100), 1)')
5.276147376280434
+10
source

Source: https://habr.com/ru/post/1610997/


All Articles