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.
精彩评论