开发者

Python dictionary manipulation

I got a list of object

lst = [1,2,3]

I want them in a dictionary with a default key 'number', and then put them in a list.

The result should look like

lst = [{'number':1},{'number':2},{'number':3}
开发者_开发问答

Use less code, please.


Use a list comprehension

lst = [{'number': x} for x in lst]


This matches your code samples:

>>> lst = [1,2,3]
>>> newlst = [dict(number=n) for n in lst]
>>> newlst
[{'number': 1}, {'number': 2}, {'number': 3}]
>>> 

What you say, however, is a bit different - you want them all in the same dictionary, or each in a dictionary of its own? The snippet above gives you the latter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜