Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

and a list like:

list1 = [3, 6]

I'd like to update dict1 or create another list as follows:

dict1 = [{'domain':'Ratios', 'count':3}, {'domain':'Geometry', 'count':6}]

How would I do this?

like image 513
Harshil Parikh Avatar asked May 15 '12 00:05

Harshil Parikh


People also ask

How do I update a list of dictionaries?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')

What happens if you assign a new value to a dictionary using a key that already exists?

In Python, you can add a new item to the dictionary dict with dict_object[key] = new_value . In this way, if the key already exists, the value is updated (overwritten) with the new value.


2 Answers

>>> 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'}]
like image 141
jamylak Avatar answered Oct 23 '22 19:10

jamylak


You could do this:

for i, d in enumerate(dict1):
    d['count'] = list1[i]
like image 44
larsks Avatar answered Oct 23 '22 20:10

larsks