将列表更改为字典

时间:2014-11-25 05:56:57

标签: python

我正在尝试将[["bill", 21], ["kevin", 42], ["gail",20]]格式的列表更改为{"bill":21, "kevin":42, "gail":20}格式的字典。有一个简单的方法吗?

3 个答案:

答案 0 :(得分:3)

dict()构造函数采用可迭代的2个大小的迭代。因此,您只需在列表中拨打dict

In [11]: L = [['bill', 21], ['kevin', 42], ['gail',20]]

In [12]: dict(L)
Out[12]: {'bill': 21, 'kevin': 42, 'gail': 20}

答案 1 :(得分:2)

In [2]: l = [['bill', 21], ['kevin', 42], ['gail',20]]

In [3]: d = dict(l)
In [4]: d
Out[4]: {'gail': 20, 'bill': 21, 'kevin': 42}

答案 2 :(得分:2)

要将字典值转换为整数,请使用以下代码:

>>> text=[["bill", '21'], ["kevin", '42'], ["gail",'20']]
>>> dict([[i,int(j)] for i,j in text])
{'bill': 21, 'kevin': 42, 'gail': 20}