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
user3864194
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
Marcin
source
to share
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
inspectorG4dget
source
to share
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
Irshad Bhat
source
to share