Jay
Jay

Reputation: 67

How to spread elements of an array into keys of a dictionary? Python

I have an array

a = [1,2,3,4]

And i want to spread the elements 1,2,3,4 into keys of a dict so that I get

_dict = {1:None, 2:None, 3:None, 4:None}

How can I do it more efficiently than:

for el in a:
    _dict[el] = None

Upvotes: 3

Views: 1445

Answers (3)

Aguy
Aguy

Reputation: 169

You can assign new values to a dict by typing dict[key] = value The best way I can think of doing this is

dict = {key: None for key in a}
# Or
for key in a:
    dict[key] = None

Upvotes: 1

Mureinik
Mureinik

Reputation: 311998

You can use the fromkeys method:

d = dict.fromkeys(a)

Upvotes: 4

MaBekitsur
MaBekitsur

Reputation: 181

You can do the following:

_dict = {key: None for key in a}

Upvotes: 3

Related Questions