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 get multiple specific keys and values from list of dictionaries

I have the following data:

data={
     "locations": [
         {
             "id": "27871f2d-101c-449e-87ad-36a663b144fe",
             "switch_id": 20,
             "switch_port": 16,
             "vlan_id": 101,
         },
         {
             "id": "94b1d7a2-7ff2-4ba3-8259-5eb7ddd09fe1",
             "switch_id": 6,
             "switch_port": 24,
             "vlan_id": 203,
         },
     ]
}

And what I want to do is extract ‘id’ and ‘vlan_id’ into a new dictionary with a list of sub dictionaries, like this:

new_data={
     "connections": [
         {
             "id": "27871f2d-101c-449e-87ad-36a663b144fe",
             "vlan_id": 101,
         },
         {
             "id": "94b1d7a2-7ff2-4ba3-8259-5eb7ddd09fe1",
             "vlan_id": 203,
         },
     ]
}

My initial thoughts were as a dictionary comprehension like this:

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

new_data = {"connections": [some code here]}

But not sure of the some code bit yet.

>Solution :

Try:

new_data = {"connections": [{'id': d['id'], 'vlan_id': d['vlan_id']} for d in data['locations']]}
{'connections': [{'id': '27871f2d-101c-449e-87ad-36a663b144fe', 'vlan_id': 101}, {'id': '94b1d7a2-7ff2-4ba3-8259-5eb7ddd09fe1', 'vlan_id': 203}]}
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