Modifying a list in a dictionary

I'm trying to modify a formatted list in a formatted [["bill", 21], ["kevin", 42], ["gail",20]]

dictionary {"bill":21, "kevin":42, "gail":20}

. Is there an easy way to do this?

+3


source to share


3 answers


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


source


The constructor dict()

accepts a two-size iterable iteration. This way you can just call dict

on your list:



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

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

      

+3


source


To convert dictionary values to integers use this code:

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

      

+2


source







All Articles