开发者

Oneline population of dictionary from array in Python

开发者 https://www.devze.com 2023-03-17 22:15 出处:网络
I need to populate dictionary from array开发者_如何学JAVA. I\'ve done in three lines and i\'m trying to do it shortest as it can be. Is there way how to populate it in single line?

I need to populate dictionary from array开发者_如何学JAVA. I've done in three lines and i'm trying to do it shortest as it can be. Is there way how to populate it in single line?

a = [['test',154],['test2',256]]
d = dict()
for b in a:
    d[b[0]] = b[1]


Just dict :)

>>> a = [['test',154],['test2',256]]
>>> dict(a)
{'test': 154, 'test2': 256}


You just do dict(a) or dict([['test',154],['test2',256]]).


L = [['test',154],['test2',256]]

In Python 3.x:

d = {k:v for k,v in L}

In Python 2.x:

d = dict([(k,v) for k,v in L])
0

精彩评论

暂无评论...
验证码 换一张
取 消