-1

Here I am trying to update the the list of dictionary like this but I am not getting the desired output. How can I solve this ?

 def get_values(self):

    list1 =  [{'key1': 'value1'}, {'key2': 'value2'}]

    list2 = [100, 200]
    for i in list1:
        for j in list2:
            i['val']=j
    return list1

The current output is

[{"key1": "value1","val": 200},{"key2": "value2","val": 200}],

The output I want is:

[{"key1": "value1","val": 100},{"key2": "value2","val": 200}],
D_P
  • 802
  • 10
  • 32

3 Answers3

1

You can write a list comprehension using zip() to achieve this. Below are few alternatives to achieve this in different Python versions.

In Python 3.9.0+, using |:

>>> list1 =  [{'key1': 'value1'}, {'key2': 'value2'}]
>>> list2 = [100, 200]

>>> [l1 | {'val': v} for l1, v in zip(list1, list2)]
[{'key1': 'value1', 'val': 100}, {'key2': 'value2', 'val': 200}]

In Python 3.5+ using **

>>> [{**l1, 'val': v} for l1, v in zip(list1, list2)]
[{'key1': 'value1', 'val': 100}, {'key2': 'value2', 'val': 200}]

Issue with your code is that your are doing nested iteration of list list2 for both the values of list1, because of which 'val' is firstly getting set as 100 and then 200, and your dictionaries are preserving the last value of list2 i.e. 200. zip() will let you iterate both the iterables together by fetching element corresponding to same index from both the lists.

Hence, you code using explicit for loop could be written using zip() as:

list1 =  [{'key1': 'value1'}, {'key2': 'value2'}]
list2 = [100, 200]

for i, j in zip(list1, list2):
    i['val'] = j
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

You need to iterate over both lists at the same time.

Python has a function zip useful for this. It pairs together each position in two (or more) sequences.

In this example we're using strings here as sequences of characters, just to be brief:

>>> list(zip('abc', '123'))
[('a', '1'), ('b', '2'), ('c', '3')]

So, you can fix your function:

def get_values(self):

    list1 =  [{'key1': 'value1'}, {'key2': 'value2'}]

    list2 = [100, 200]
    
    for d, n in zip(list1, list2):
        d['val'] = n

    return list1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

You can do this also without zip

list1 =  [{'key1': 'value1'}, {'key2': 'value2'}]
list2 = [100, 200]


for index, dictionary in enumerate(list1):
    dictionary['val']=list2[index]

print(list1)
ble
  • 287
  • 1
  • 5