Updating a list of python dictionaries with a key, value pair from another list

前端 未结 4 1983
青春惊慌失措
青春惊慌失措 2021-02-19 19:35

Let\'s say I have the following list of python dictionary:

dict1 = [{\'domain\':\'Ratios\'},{\'domain\':\'Geometry\'}]

and a list like:

4条回答
  •  独厮守ぢ
    2021-02-19 20:19

    You can do this:

    # list index
    l_index=0
    
    # iterate over all dictionary objects in dict1 list
    for d in dict1:
    
        # add a field "count" to each dictionary object with
        # the appropriate value from the list
        d["count"]=list1[l_index]
    
        # increase list index by one
        l_index+=1
    

    This solution doesn't create a new list. Instead, it updates the existing dict1 list.

提交回复
热议问题