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

前端 未结 4 1984
青春惊慌失措
青春惊慌失措 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:02
    >>> l1 = [{'domain':'Ratios'},{'domain':'Geometry'}]
    >>> l2 = [3, 6]
    >>> for d,num in zip(l1,l2):
            d['count'] = num
    
    
    >>> l1
    [{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]
    

    Another way of doing it, this time with a list comprehension which does not mutate the original:

    >>> [dict(d, count=n) for d, n in zip(l1, l2)]
    [{'count': 3, 'domain': 'Ratios'}, {'count': 6, 'domain': 'Geometry'}]
    
    0 讨论(0)
  • 2021-02-19 20:04

    Using list comprehension will be the pythonic way to do it.

    [data.update({'count': list1[index]}) for index, data in enumerate(dict1)]
    

    The dict1 will be updated with the corresponding value from list1.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 20:27

    You could do this:

    for i, d in enumerate(dict1):
        d['count'] = list1[i]
    
    0 讨论(0)
提交回复
热议问题