Maltesse Maltesse - 17 days ago 4
Python Question

Python Dictionary combining by current expression

I have two dictionaries:

x = [{'policy': 'a-b-windows2007', 'starttime': '4', 'duration': '5'},
{'policy': 'ab-server2012', 'starttime': '4', 'duration': '5'},
{'policy': 'Aa-windows', 'starttime': '4', 'duration': '5'}]

y = [{'policy': 'Windws a-b-windows2007', 'total_hosts': '160'},
{'policy': 'Windows ab-server2012', 'total_hosts': '170'},
{'policy': 'Windows Aa-windows', 'total_hosts': '180'}]


I want to have one dict by combining x and y if policy in x = policy in y. I have created regex and I am struggling how to merge them

x and y are not the same length.

My attempt so far:

for key in x:
for keys in y:
if key['policy'] == re.match('[0-9]+|\b[a-z-]+(\d)',keys['policy']):
z.update(y)


Wanted output:

z=[{policy: 'a-b-windows2007',starttime: '4', duration: '5',total_hosts:'160'},
{policy: 'ab-server2012',starttime: '4', duration: '5',total_hosts:'170'},
{policy: 'Aa-windows',starttime: '4', duration: '5',total_hosts:'180'}]

Answer

Your regex wasn't working for me, here's a nested for loop solution assume t hat your policy follows: this format <windows> <version_number> we split the policy value and take the version_number to compare, you can easily convert it to a dict comprehension if you so wish too..

x = [{'policy': 'a-b-windows2007',  'starttime': '4', 'duration': '5'}, 
     {'policy': 'ab-server2012', 'starttime': '4', 'duration': '5'}, 
     {'policy': 'Aa-windows', 'starttime': '4', 'duration': '5'}]

y = [{'policy': 'Windows a-b-windows2007', 'total_hosts': '160'},
     {'policy': 'Windows ab-server2012', 'total_hosts': '170'},
     {'policy': 'Windows Aa-windows', 'total_hosts': '180'}]

for x_dict in x:
    for y_dict in y:
        if x_dict['policy'] == y_dict['policy'].split(' ')[1]:
            if "total_hosts" in x_dict:
                x_dict["total_hosts"].append(y_dict["total_hosts"])
            else:
                x_dict["total_hosts"] = y_dict["total_hosts"]

print(x)

Gives:

[{'starttime': '4', 'duration': '5', 'policy': 'a-b-windows2007', 'total_hosts': '160'}, 
{'starttime': '4', 'duration': '5', 'policy': 'ab-server2012', 'total_hosts': '170'}, 
{'starttime': '4', 'duration': '5', 'policy': 'Aa-windows', 'total_hosts': '180'}]

This solution updates the x list so if you want a new list without changing x, just make a copy of x to change called z and change the for loops where ever x is make it to z...

Comments