Search code examples
python-3.xdictionaryarraylistkeykey-value

Making a list of dict from a list of lists with the list[0] as keys and other lists as values


could you tell me how can I get a list of dicts from that with the a[0] as keys for each dict and a[1:] as values accordingly.

a = [['PORT', 'NAME', 'STATUS', 'VLAN', 'DUPLEX', 'SPEED', 'TYPE', 'FC_MODE'], ['Gi1/0/1', 'S1-P1-01 Cisco_Roo', 'connected', '248', 'a-full', 'a-1000', '10/100/1000BaseTX', ''], ['Gi1/0/2', '', 'notconnect', '121', 'auto', 'auto', '10/100/1000BaseTX', ''], ['Gi1/0/3', '', 'notconnect', '121', 'auto', 'auto', '10/100/1000BaseTX', '']]

I wanna get

[{'PORT' : 'Gi1/0/1', 'NAME' : 'S1-P1-01 Cisco_Roo', . . . }, {'PORT' : 'Gi1/0/2', 'NAME' : '', .
.
.
}]


Solution

  • The easiest is probably:

    [dict(zip(a[0], x)) for x in a[1:]]
    

    This walks through each element from 1 onwards, and combines it with the first element, converting to a dictionary.