How to Merge Two Lists of Dictionaries in Python Using ** Unpacking
This guide shows how to combine two lists of dictionaries into a single list of merged dictionaries in Python by leveraging the {**dict1, **dict2} unpacking syntax together with zip and list extension, providing clear code examples and explanations.
A student wanted to merge two lists of dictionaries, l1 and l2, into a single list where each element is a dictionary containing the keys from both original dictionaries.
l1 = [{x: x} for x in range(10)]
l2 = [{x: x} for x in range(10, 20)]The desired result looks like:
[{0: 0, 10: 10}, {1: 1, 11: 11}, {2: 2, 12: 12}, {3: 3, 13: 13}, {4: 4, 14: 14}, {5: 5, 15: 15}, {6: 6, 16: 16}, {7: 7, 17: 17}, {8: 8, 18: 18}, {9: 9, 19: 19}]Python 3.5+ provides a convenient syntax for merging dictionaries: {**x, **y}. For example, merging two simple dictionaries:
d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
# Resulting dictionary, with later keys overriding earlier ones
d3 = {**d1, **d2} # {'a': 1, 'b': 2, 'c': 3, 'd': 4}Using this syntax, we can merge the dictionaries inside l1 and l2 as follows:
l3 = []
for x, y in zip(l1, l2):
l3.extend([{**x, **y}])
print(l3)This code zips the two lists, merges each pair of dictionaries with the {**x, **y} unpacking, and extends l3 with the merged dictionaries, producing the desired combined list.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
