'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:

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

But not sure of the some code bit yet.



Solution 1:[1]

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}]}

Solution 2:[2]

You can create the new_data variable accesing the first dictionary data like this:

new_data={
         "connections": [
             {
                 "id": data['locations'][0]['id'],
                 "vlan_id": data['locations'][0]['vlan_id'],
             },
             {
                 "id": data['locations'][1]['id'],
                 "vlan_id": data['locations'][1]['vlan_id'],
             },
         ]
    }

edit: You can get a more dynamic approach by reading every object in the list with a forloop like this:

new_data={
         "connections": []
    }

for object in data['locations']:
    new_dict = {
        "id": object["id"],
        "vlan_id": object["vlan_id"]
    }
    new_data['connections'].append(new_dict)

Solution 3:[3]

Following Marc's answer here, you could modify it to

new_data = {}
for i in range(len(data['locations'])):
    if "connections" not in new_data.keys():
        new_data['connections'] = [{"id": data['locations'][i]['id'],"vlan_id": data['locations'][i]['vlan_id']}]
    else:
        new_data['connections'].append({"id": data['locations'][i]['id'],"vlan_id": data['locations'][i]['vlan_id']})

Solution 4:[4]

The Answers here are good but you can make the code more dynamic

keys_to_extract = ['id', 'vlan_id']

locations = data['locations']
connections = { key: val for key, val in locations.items() if key in keys_to_extract }

new_data = {'connections': connections}

Now you can change the keys you need on the fly

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AloneTogether
Solution 2
Solution 3 Conrad747
Solution 4 Jerome Paddick