简体   繁体   中英

How to create a new dictionary from two other dictionaries taking different keys and values with iteration?

I have two dictionaries as input. The first one contains pin numbers as keys and as values - the probability of a certain code.

`dict_1={
8063: {'code15': 99.61, 'code17': 96.14}, 9621: {'15': 88.59}, 1583: {'code17': 99.37, 'code14':87.37}, 
7631: {'code17': 99.88}, 4345: {'code11': 99.97, 'code12': 99.93},  1799: {'code11': 99.8,   'code12': 99.18},
3604: {'code17': 98.77}, 1098: {'code12': 99.96}, 3752: {'code11': 99.95}}`

The second one has clusters as keys with list of pin numbers and names in a dictionary as values.

`dict_2={ 0: {
'count': 4,
'id': [{'pin': 8063,'name': 'John'},
            {'pin': 9621,'name': 'Maria'},
            {'pin': 1583,'name': 'Peter'},
           {'pin': 7631,'name': 'Jess'}]},
3: {
'count': 5,
'id': [
        {'pin': 4345,'name': 'George'},
        {'pin': 1799,'name': 'Kevin'},
           {'pin': 3604,'name': 'Sarah'},
            {'pin': 1098,'name': 'Stewie'},
            {'pin': 3752, 'name': 'Jan'}]}
}`

I want to create a dictionary that has the clusters from dict_2 as keys and as values - a dictionary with the codes from dict_1 as keys and the probability, pins and names in a list as values. This should be the output:

`merged_dict =    {
0: {'code15': [99.61, 8063, 'John', 88.59, 9621,'Maria'],
'code17':[99.37, 1583, 'Peter', 96.14, 8063, 'John',99.88, 7631, 'Jess', 98.77, 3604, 'Sarah'],
'code14':[87.37, 1583, 'Peter'] },
3: {'code11': [99.97, 4345, 'George', 99.8,  1799, 'Kevin', 99.95, 3752, 'Jan'],
'code12':[99.93, 4345, 'George', 99.18,  1799, 'Kevin', 99.96,  1098, 'Stewie']}
}`

I've tried to append merge the dictionaries by pin as a common element, but no success.

Below is a solution function to achieve the result:

def merge_dict(dict_1, dict_2):
    dict_3 = {}
    for cluster, data in dict_2.items():
        dict_3[cluster] = {}
        for pin in data['id']:
            for code, prob in dict_1[pin['pin']].items():
                if code in dict_3[cluster]:
                    dict_3[cluster][code][0] += prob
                    dict_3[cluster][code].append(pin['pin'])
                    dict_3[cluster][code].append(pin['name'])
                else:
                    dict_3[cluster][code] = [prob, pin['pin'], pin['name']]
    return dict_3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM