I have two lists of rows, each with two rows, like this:
list1 = [{'a': 'foo', 'b': 'bar', 'c': 'baz'}, {'d': 'qux', 'e': 'quux', 'f': 'quuz'}]
list2 = [{'g': 'corge', 'h': 'grault', 'i': 'garply'}, {'j': 'waldo', 'k': 'fred', 'l': 'plugh'}]
I would like to join the two lists so that row 1 from list 1 is joined with row 1 from list 2 and row 2 from list 1 is joined with row 2 from list 2, like this:
final_list = [{'a': foo, 'b': bar 'c': baz, 'g': corge, 'h': grault, 'i': garply}, {'d': qux, 'e': quux, 'f': quuz, 'j': waldo, 'k': fred, 'l': plugh}]
I have tried:
final_list = [[i, j] for i,j in zip(list1, list2)]
But it doesn't quite join them correctly. Instead, it produces:
[{'a': foo, 'b': bar 'c': baz}, {'g': corge, 'h': grault, 'i': garply}], [{'d': qux, 'e': quux, 'f': quuz}, {'j': waldo, 'k': fred, 'l': plugh}]
I would like to join these lists of rows so that I can then loop through them with Jinja on an HTML page. How can I resolve this issue?
CodePudding user response:
Your list comprehension should be creating a new dictionary, rather than a list of dictionaries, for each element in the result from zip()
:
list1 = [
{'a': 'foo', 'b': 'bar', 'c': 'baz'},
{'d': 'qux', 'e': 'quux', 'f': 'quuz'}
]
list2 = [
{'g': 'corge', 'h': 'grault', 'i': 'garply'},
{'j': 'waldo', 'k': 'fred', 'l': 'plugh'}
]
# Can also use "x | y" in place of "{**x, **y}" if on Python 3.9
result = [{**x, **y} for x, y in zip(list1, list2)]
print(result)
This outputs:
[
{'a': 'foo', 'b': 'bar', 'c': 'baz', 'g': 'corge', 'h': 'grault', 'i': 'garply'},
{'d': 'qux', 'e': 'quux', 'f': 'quuz', 'j': 'waldo', 'k': 'fred', 'l': 'plugh'}
]
CodePudding user response:
You can actually use the update
function which can be used to merge two python dictionaries and is very simple and easy to use.
a = [
{"a": "foo", "b": "bar", "c": "baz"},
{"d": "qux", "e": "quux", "f": "quuz"},
]
b = [
{"g": "corge", "h": "grault", "i": "garply"},
{"j": "waldo", "k": "fred", "l": "plugh"},
]
for i in range(len(a)):
a[i].update(b[i])
print(a)
The output is as
[{'a': 'foo', 'b': 'bar', 'c': 'baz', 'g': 'corge', 'h': 'grault', 'i': 'garply'}, {'d': 'qux', 'e': 'quux', 'f': 'quuz', 'j': 'waldo', 'k': 'fred', 'l': 'plugh'}]
CodePudding user response:
Your items are dictionary objects…
You can create a new dict out of the two… the keys of the last dict will overwrite the values if any are the same. The below is using the dict
unpacking operator **
.
final_lst = [{**d1, **d2} for d1, d2 in zip(lst1, lst2)]
There are other ways as well. Removed first example as it wasn’t correct.