-5

I have two lists of equal length, as follows:

l1 = [{'a': 'foo'}, {'a': 'foo'}, {'a': 'bar'}, {'a': 'bar'}]
l2 = [{'b': 'foo'}, {'b': 'bar'}, {'b': 'foo'}, {'b': 'bar'}]

I would like to combine these lists so that the key and value of each index position is in the same dictionary in a third list, i.e.:

l3 = [{'a': 'foo', 'b': 'foo'}, {'a':'foo', 'b':'bar'}, {'a':'bar', 'b':'foo'}, {'a':'bar', 'b':'bar'}]

How can I achieve this? I have tried with the following code:

l3 = [] 
mydict = {} 
index = 0 
while index < len(l1):     
    mydict['a'] = l1[index]['a']     
    mydict['b'] = l2[index]['b']     
    l3.append(mydict)     
    index +=1

but this returns:

[{'a': 'bar', 'b': 'bar'}, {'a': 'bar', 'b': 'bar'}, {'a': 'bar', 'b': 'bar'}, {'a': 'bar', 'b': 'bar'}]
Steve
  • 25
  • 4
  • Make an attempt. – Ant Dec 15 '22 at 03:49
  • 1
    I assume that if you have `{'a': 'foo'}` and `{'b': 'foo'}`, you can see how to write code that would form `{'a': 'foo', 'b': 'foo'}` from those inputs; and I assume you know how to write list comprehensions and/or `for` loops. The remaining challenge is to get those pairs of values, one pair each time through the loop; this is covered by the linked duplicate. – Karl Knechtel Dec 15 '22 at 03:52
  • 1
    (If you need help with those steps, I can think of existing duplicates for them, too.) – Karl Knechtel Dec 15 '22 at 03:52

1 Answers1

0

I was able to achieve this with the following:

index=0
while index < len(l1):     
    l1[index].update(l2[index])
    index +=1
print(l1)
NameVergessen
  • 598
  • 8
  • 26
Steve
  • 25
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – lemon Dec 18 '22 at 21:22
  • @lemon How is this unclear? It's trivial code. Even written in unpythonic style that's easy to understand for people who only know other languages like C/C++/Java. – Kelly Bundy Dec 18 '22 at 21:47
  • Explaining the reasoning behind how they crafted this solution can improve the overall quality of the answer and be way better than "*I was able to achieve this with the following:*", even if the code can be easy to understand. @KellyBundy – lemon Dec 18 '22 at 21:48
  • @lemon Besides being trivial, it's also just a minor modification of the question's code. Most of this code was already there. I really can't imagine what you want them to say about it. – Kelly Bundy Dec 18 '22 at 21:51
  • @Steve The pythonic way to do the same thing would btw be `for d1, d2 in zip(l1, l2): d1.update(d2)` – Kelly Bundy Dec 18 '22 at 21:59