Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python converting a list into a dict with a value of 1 for each key [duplicate]

Tags:

python

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?

like image 584
ealeon Avatar asked Dec 24 '22 13:12

ealeon


1 Answers

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
like image 159
Morgan Thrapp Avatar answered Apr 28 '23 03:04

Morgan Thrapp