In Python 3.9, I have a list of dictionaries:
variables = [
{'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'},
{'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'}
]
My goal is to transform it into this dictionary format:
result = {
'alpha.ip': '10.10.10.10',
'alpha.name': 'primary',
'beta.ip': '10.10.10.20',
'beta.name': 'secondary',
'gamma.ip': '10.10.10.20',
'gamma.name': 'secondary'
}
I have a difficult time drafting the id
loop logic, which will produce the correct result.
You need to iterate through the variables
list and, for each entry, loop through its id
list. For each id
, you will then generate two key-value pairs: one for the IP
and one for the name
.
variables = [
{'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'},
{'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'}
]
result = {}
for var in variables:
for id_value in var['id']:
result[f"{id_value}.ip"] = var['ip']
result[f"{id_value}.name"] = var['name']
print(result)
which derives:
{
'alpha.ip': '10.10.10.10',
'alpha.name': 'primary',
'beta.ip': '10.10.10.20',
'beta.name': 'secondary',
'gamma.ip': '10.10.10.20',
'gamma.name': 'secondary'
}
0
Though it may be excessively “clever” this transformation can be accomplished with dictionary comprehensions. The nested loop structures seen in mrconcerned’s answer can be seen replicated in the comprehensions, but because side-effects are eschewed, there is less room for the dictionaries to be unintentionally modified in some way by a mistake.
{
**{
f"{id}.ip": entry['ip']
for entry in variables
for id in entry['id']
},
**{
f"{id}.name": entry['name']
for entry in variables
for id in entry['id']
}
}
Resulting value:
{
'alpha.ip': '10.10.10.10',
'beta.ip': '10.10.10.20',
'gamma.ip': '10.10.10.20',
'alpha.name': 'primary',
'beta.name': 'secondary',
'gamma.name': 'secondary'
}
This does require multiple passes over the variables
data, but that is already present in the original approach using dict.update
.
1