将列表制作成字典

时间:2016-07-02 21:09:42

标签: python list dictionary

我有一个像这样的列表

list = [('a', 3418), ('b', 3544), ('c', 1153), ('d', 2155), ('e', 2254), ('f', 2654), ('g', 2982), ('h', 3267), ('i', 3056), ('j', 820), ('k', 2987)]

我需要得到这样的字典:

dictionary = {'a' : 3418, 'b' : 3544, 'c' : 1153}

尝试使用

dict = {k:v for k,v in (x.split(',') for x in list) }

但得到错误

  

AttributeError:' tuple'对象没有属性' split'

2 个答案:

答案 0 :(得分:3)

最简单的方法:

In [1]: x =  [('a', 3418), ('b', 3544), ('c', 1153), ('d', 2155), ('e', 2254), ('f', 2654), ('g', 2982), ('h', 3267), ('i', 3056), ('j', 820), ('k', 2987)]

In [2]: dict(x)
Out[2]: 
{'a': 3418,
 'b': 3544,
 'c': 1153,
 'd': 2155,
 'e': 2254,
 'f': 2654,
 'g': 2982,
 'h': 3267,
 'i': 3056,
 'j': 820,
 'k': 2987}

来自dict docstring:

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v

答案 1 :(得分:0)

最简单的方法,恕我直言,将使用词典理解:

>>> l = [('a', 3418), ('b', 3544), ('c', 1153), ('d', 2155), ('e', 2254), ('f', 2654), ('g', 2982), ('h', 3267), ('i', 3056), ('j', 820), ('k', 2987)]
>>> d = {x[0] : x[1] for x in l}
>>> d
{'a': 3418, 'c': 1153, 'b': 3544, 'e': 2254, 'd': 2155, 'g': 2982, 'f': 2654, 'i': 3056, 'h': 3267, 'k': 2987, 'j': 820}