-2

I have two dict. The elements in the dicts come in order.

[{'macaddress': 'xx:xx:xx:xx:xx:xx'}, {'macaddress': 'cc:cc:cc:cc:cc:cc'}]
[{'ipaddress': '192.168.1.1'}, {'ipaddress': '192.168.1.2'}]

I want to combine them as I show below;

[
 {
   'macaddress': 'xx:xx:xx:xx:xx:xx', 
   'ipaddress': '192.168.1.1'
 }, 
 { 
   'macaddress': 'cc:cc:cc:cc:cc:cc', 
   'ipaddress': '192.168.1.2'
 }
]

How can I do that? Thanks.

  • 1
    [I downvoted your question because no attempt was made](http://idownvotedbecau.se/noattempt). – martineau Jul 04 '22 at 19:55
  • Does this answer your question? [Python: Merge two lists of dictionaries](https://stackoverflow.com/questions/19561707/python-merge-two-lists-of-dictionaries) – TheFungusAmongUs Jul 04 '22 at 20:39

3 Answers3

2

For python 3.9+, you can use | operator between two dicts:

macs = [{'macaddress': 'xx:xx:xx:xx:xx:xx'}, {'macaddress': 'cc:cc:cc:cc:cc:cc'}]
ips = [{'ipaddress': '192.168.1.1'}, {'ipaddress': '192.168.1.2'}]

output = [mac | ip for mac, ip in zip(macs, ips)]
print(output)
# [{'macaddress': 'xx:xx:xx:xx:xx:xx', 'ipaddress': '192.168.1.1'}, {'macaddress': 'cc:cc:cc:cc:cc:cc', 'ipaddress': '192.168.1.2'}]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
2

Assuming l1 and l2 the two lists, you can use zip and a list comprehension with dictionary expansion:

l1 = [{'macaddress': 'xx:xx:xx:xx:xx:xx'}, {'macaddress': 'cc:cc:cc:cc:cc:cc'}]
l2 = [{'ipaddress': '192.168.1.1'}, {'ipaddress': '192.168.1.2'}]

out = [{**d1, **d2} for d1, d2 in zip(l1, l2)]

Output:

[{'macaddress': 'xx:xx:xx:xx:xx:xx', 'ipaddress': '192.168.1.1'},
 {'macaddress': 'cc:cc:cc:cc:cc:cc', 'ipaddress': '192.168.1.2'}]
mozway
  • 194,879
  • 13
  • 39
  • 75
-2

Update

Please ignore this solution as it is incorrect.

Solution

Your question really is asking how to merge two different lists. You can simply merge them by doing:

a = [{'macaddress': 'xx:xx:xx:xx:xx:xx'}, {'macaddress': 'cc:cc:cc:cc:cc:cc'}]
b = [{'ipaddress': '192.168.1.1'}, {'ipaddress': '192.168.1.2'}]
c = a + b

However, there are many ways to merge lists. For more information, please check out this list of eight different ways of merging lists.

E. Turok
  • 106
  • 1
  • 7
  • I didn't downvote, but note OP wants to merge corresponding dictionaries in the two lists. Your code appends the two lists. – DarrylG Jul 04 '22 at 19:37