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

Transform a list of dictionaries, based on key list

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. With my limited Python experience, using the name instead of id:

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

result = {}
variables = [
    {'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'},
    {'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'}
]
ips = {f"{x['name']}.ip": x['ip'] for x in variables}
result.update(ips)
names = {f"{x['name']}.name": x['name'] for x in variables}
result.update(names)

>Solution :

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