limitless
limitless

Reputation: 669

How to make a dictionary from list

let's say I have a list, how can I create a dictionary, where the object in the list is the keys, and ill choose one value as default. for example :

inp : [a,b,c]
out : {a:1,b:1,c:1}

all i can think of is this :

dict={}
list=['a','b','c']
for obj in list:
    dict[obj]=1

is there any cleaner way ? thank you.

Upvotes: 3

Views: 94

Answers (2)

Iron Fist
Iron Fist

Reputation: 10951

You can also do it this way:

>>> lst = ['a','b','c']
>>> dict(zip(lst,[1]*len(lst)))
{'a': 1, 'c': 1, 'b': 1}

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can use fromkeys as ints are immutable:

d = dict.fromkeys(l, 1)

Demo:

In [6]: l = ['a','b','c']

In [7]: dict.fromkeys(l, 1)
Out[7]: {'a': 1, 'b': 1, 'c': 1}

Why immutability makes a difference can be seen by using a mutable object as a value i.e a list:

In [10]: d = dict.fromkeys(l, [])

In [11]: d["a"].append("foo")

In [12]: d
Out[12]: {'a': ['foo'], 'b': ['foo'], 'c': ['foo']}

A mutable value will be shared.

You could also use a dict comprehension which would be safe for either a mutable or immutable value:

d = {k: [] for k in l}
d = {k: 1 for k in l}

Upvotes: 7

Related Questions