12

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?

Harshil Parikh
  • 291
  • 2
  • 3
  • 8
  • According to the example, the title to this question should be: "Updating a list of python dictionaries values from another list". From the current title I would expect that list1 = [('Ratios', 3), ('Geometry', 6)] – yucer Dec 12 '16 at 09:20

4 Answers4

23
>>> 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'}]
jamylak
  • 128,818
  • 30
  • 231
  • 230
6

You could do this:

for i, d in enumerate(dict1):
    d['count'] = list1[i]
jamylak
  • 128,818
  • 30
  • 231
  • 230
larsks
  • 277,717
  • 41
  • 399
  • 399
3

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.

Thanasis Petsas
  • 4,378
  • 5
  • 31
  • 57
0

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.

Jason Sundram
  • 12,225
  • 19
  • 71
  • 86
dan-boa
  • 590
  • 4
  • 10
  • 1
    -1 Using a list comprehension for mutations is **not** pythonic. Use a simple for loop. – jamylak Aug 07 '12 at 08:14
  • update on a dict work on reference not provide output . data.update() return None. You will get out put as [None, None, ....] – Manoj Sahu Mar 01 '16 at 07:51