列出没有值的字典

时间:2013-03-12 20:17:52

标签: python list dictionary

如何转换列表:

['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']

进入没有值的字典:

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

3 个答案:

答案 0 :(得分:10)

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}

正如评论中 DSM 所指出的那样,你必须小心将可变对象设置为值,因为它们都指向同一个对象。改变一个,改变所有:

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]}

答案 1 :(得分:8)

像这样:

dict.fromkeys(yourlist, 0)

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

答案 2 :(得分:4)

my_dict = {elem:0 for elem in my_list}

例如:

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}