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

后端 未结 6 662
终归单人心
终归单人心 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:15

    If you want to use list comprehension, there's a great answer here: https://stackoverflow.com/a/3197365/4403872

    In your case, it would be like this:

    result = [dict(item, **{'elem':'value'}) for item in myList]
    

    Eg.:

    myList = [{'a': 'A'}, {'b': 'B'}, {'c': 'C', 'cc': 'CC'}]
    

    Then use either

    result = [dict(item, **{'elem':'value'}) for item in myList]
    

    or

    result = [dict(item, elem='value') for item in myList]
    

    Finally,

    >>> result
    [{'a': 'A', 'elem': 'value'},
     {'b': 'B', 'elem': 'value'},
     {'c': 'C', 'cc': 'CC', 'elem': 'value'}]
    

提交回复
热议问题