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

后端 未结 6 669
终归单人心
终归单人心 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 05:51

    >>> a = [ { 1:1 }, {2:2}, {3:3} ]
    >>> for item in a:
    ...     item.update( { "test": "test" } )
    ... 
    >>> a
    [{'test': 'test', 1: 1}, {'test': 'test', 2: 2}, {'test': 'test', 3: 3}]
    

    You are using a list comprehension incorrectly, the call to item.update returns a None value and thus your newly created list will be full of None values instead of your expected dict values.

    You need only to loop over the items in the list and update each accordingly, because the list holds references to the dict values.

提交回复
热议问题