Nishant Singh Nishant Singh - 1 year ago 61
Python Question

combine 2 list of dicts into one

I have two list of dicts say :


[ { 'rds_name': u'emsclassicldap', 'rds_type': u'db.m3.medium'},
{ 'rds_name': u'fra01-devops-KPX', 'rds_type': u'db.t2.medium'},
{ 'rds_name': u'prodreplica', 'rds_type': u'db.t2.medium'}


[ { 'alarm_name': u'emsclassicldap_db_connections', 'alarm_threshold': 380.0},
{ 'alarm_name': u'fra01-devops-KPX_db_connection',
'alarm_threshold': 266.0},
{ 'alarm_name': u'prodreplica_db_connections',
'alarm_threshold': 266.0},

actually has
as its substring ;I need to actually combine these two list into one based this condition so that the final result should look like

{ 'rds_name': u'emsclassicldap', 'rds_type': u'db.m3.medium','alarm_name': u'classicldap_db_connections', 'alarm_threshold': 380.0}
So on

i am writing a simple def to combine :

def combine_rds_cloudwatch(rds_detail,cloudwatch_detail):
print rds_detail,cloudwatch_detail

for rds in rds_detail:
for alarm in cloudwatch_detail:
if ????????????

Not sure how to do so

Answer Source

A more generic method..

rds_list = [{'rds_name': u'emsclassicldap', 'rds_type': u'db.m3.medium'},
            {'rds_name': u'fra01-devops-KPX', 'rds_type': u'db.t2.medium'},
            {'rds_name': u'goldenprodreplica', 'rds_type': u'db.t2.medium'}

cloudwatch_list = [{'alarm_name': u'emsclassicldap_db_connections', 'alarm_threshold': 380.0},
                   {'alarm_name': u'fra01-devops-KPX_db_connection', 'alarm_threshold': 266.0},
                   {'alarm_name': u'goldenprodreplica_db_connections', 'alarm_threshold': 266.0},

def merge_two_dicts(x, y):
    """Given two dicts, merge them into a new dict as a shallow copy.
       More info here
    z = x.copy()
    return z

def combine_list(prefix_key_list, prefix_key, keys_list, key):
    combined_list = []

    for short in prefix_key_list:
        for long in keys_list:
            if long[key].startswith(short[prefix_key]):
                result = merge_two_dicts(long, short)

    return combined_list

print(combine_list(rds_list, 'rds_name', cloudwatch_list, 'alarm_name'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download