jeudi 7 février 2019

Create dictionary from lists with condition

Here's what I have:

ports = [ 1111, 2222, 3333 ]
keys = ['port', 'target_port', 'name']
ports = [dict.fromkeys(keys, port) for port in ports]

this produces:

[
    {
        "port": 1111,
        "target_port": 1111,
        "name": 1111
    }
    xxx
]

the problem is, value of "name" needs to be a string. how can I add a condition to the list comprehension?

EDIT: all the other values have to remain integers
EDIT: my workaround for now:

for port_dict in ports:
    port_dict['name'] = str(port_dict['port'])

Aucun commentaire:

Enregistrer un commentaire