LazySloth13
LazySloth13

Reputation: 2487

List to Dictionary without Values

How can I transform a list:

['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'g9', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9', 'i1', 'i2', 'i3', 'i4', 'i5', 'i6', 'i7', 'i8', 'i9']

into a dictionary with NO values:

{'a1': None, 'a2': None, 'a3': None} #etc

Upvotes: 0

Views: 163

Answers (3)

root
root

Reputation: 80406

Docstring:
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.

In [1]: l = ['a1', 'a2', 'a3', 'a4']

In [2]: dict.fromkeys(l)
Out[2]: {'a1': None, 'a2': None, 'a3': None, 'a4': None}

In [3]: dict.fromkeys(l, 0)
Out[3]: {'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0}

As pointed out by DSM in the comments, you have to be careful with setting mutable objects as values, as they all point to the same object. Change one, change all:

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

In [6]: [id(v) for v in d.values()]
Out[6]: [171439660, 171439660, 171439660, 171439660]

In [7]: d['a1'].append(1)

In [8]: d
Out[8]: {'a1': [1], 'a2': [1], 'a3': [1], 'a4': [1]}

Upvotes: 10

Matthew Adams
Matthew Adams

Reputation: 10156

my_dict = {elem:0 for elem in my_list}

Ex:

In [2]: my_list = ['a1', 'a2', 'a3', 'a4']

In [3]: my_dict = {elem:0 for elem in my_list}

In [4]: my_dict
Out[4]: {'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0}

Upvotes: 4

Pavel Anossov
Pavel Anossov

Reputation: 62948

Like this:

dict.fromkeys(yourlist, 0)

>>> l = ['a1', 'a2', 'a3', 'a4', ...
>>> dict.fromkeys(l, 0)
{'a1': 0, 'a2': 0, 'a3': 0, 'a4': 0, ...

Upvotes: 8

Related Questions