Add an element in each dictionary of a list (list comprehension)

后端 未结 6 670
终归单人心
终归单人心 2020-11-30 05:44

I have a list of dictionaries, and want to add a key for each element of this list. I tried:

result = [ item.update({\"elem\":\"value\"}) for item in mylist          


        
6条回答
  •  时光说笑
    2020-11-30 06:01

    Either do not use a list comprehension, or return a new dict based on the original dict plus the new key:

    [dict(list(item.items()) + [("elem", "value")]) for item in mylist]
    

提交回复
热议问题