Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Combine Dict

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading