4

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?

ealeon
  • 12,074
  • 24
  • 92
  • 173

1 Answers1

10

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
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
  • 2
    A dict comprehension would also work: `{key: 1 for key in somelist}`. `dict.fromkeys` is clearly the best answer, but it's also good to know about dict comprehensions. – Steven Rumbalski Oct 09 '15 at 18:01