从列表创建简单字典

时间:2014-04-03 23:34:17

标签: python

很抱歉提出一个简单的问题:

我有以下列表:

 x = ["one", "two", "three" ]

创建此词典的最佳方法是什么:

 {"one":1, "two":1, "three":1 }

由于

3 个答案:

答案 0 :(得分:3)

使用dictionary comprehension

{key: 1 for key in x}

答案 1 :(得分:1)

print dict.fromkeys(["one","two","three"],1)

我是怎么做的...如果你真的只想从列表中制作一个字典(以加快搜索速度)

如果你不在乎你的价值是什么

print dict.fromkeys(["one","two","three"])

,它将是默认的None

这有一个额外的好处,为python< 2.7加上它很容易分辨你在做什么,字典理解总是让我想到集合理解

答案 2 :(得分:0)

我要推断并猜测你正在寻找Counter

>>> from collections import Counter
>>> x = ["one", "two", "three" ]
>>> Counter(x)
Counter({'three': 1, 'two': 1, 'one': 1})