Nishant Singh Nishant Singh - 9 months ago 46
Python Question

combine 2 list of dicts into one

I have two list of dicts say :

rds_detail:

[ { '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'}
]


cloudwatch_detail:

[ { '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},
]


The
alarm_name
actually has
rds_name
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 http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression?rq=1
    """
    z = x.copy()
    z.update(y)
    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)
                combined_list.append(result)

    return combined_list


print(combine_list(rds_list, 'rds_name', cloudwatch_list, 'alarm_name'))