Home > OS >  Getting error when doing re-mapping dict keys to another dict keys in python
Getting error when doing re-mapping dict keys to another dict keys in python

Time:03-04

below is my code:

mapping_dict = {"NET_D":
                    [
                        ("name", "tiN"),  
                        ("d_id", "id"),
                        ("m_ip", "ti_ip"),
                        ("model", "cmbM"),
                        ("dc", "cmbL"), 
                        ("vendor", "cmbV"), 
                        ("cab", "cmbC")
                    ]
              }

obj = {"ti_ip": "1.1.1.1", "cmbM": "model-a", "tiN": "device-123", "cmbV": "Systems", "cmbCt": "406", "cmbC": "sc", "id": "199"}

def process_results(item_list, mapping):
    results = []
    for i in item_list:
        item = {}
        for m in mapping:
            try:
                item[m[0]] = i[m[1]]
            except KeyError:
                item[m[0]] = ""
        results.append(item)
    return results, len(results)

process_results(obj, mapping_dict["NET_D"])

desired/wanted output:

{"m_ip": "1.1.1.1", "model": "model-a", "name": "device-123", "vendor": "Systems", "cab": "406", "dc": "sc", "d_id": "199"}

error i am getting:

 process_results
    item[m[0]] = i[m[1]]
TypeError: string indices must be integers

can anyone suggest the right way to achieve desired/wanted output i am still new to python, apologies for the mistakes/errors or if my code sounds like silly/dumb ;-) to you

CodePudding user response:

You could do this, although technically your mapping_dict is a list of tuples and not a nested dict.

mapping_dict = {"NET_D":
                    [
                        ("name", "tiN"),  
                        ("d_id", "id"),
                        ("m_ip", "ti_ip"),
                        ("model", "cmbM"),
                        ("dc", "cmbL"), 
                        ("vendor", "cmbV"), 
                        ("cab", "cmbC")
                    ]
              }

obj = {"ti_ip": "1.1.1.1", "cmbM": "model-a", "tiN": "device-123", "cmbV": "Systems", "cmbCt": "406", "cmbC": "sc", "id": "199"}

def process_results(item_list, mapping):
    return {i[0]:v for k,v in item_list.items() for i in mapping if k == i[1]}

which will give

{'m_ip': '1.1.1.1', 'model': 'model-a', 'name': 'device-123', 'vendor': 'Systems', 'cab': 'sc', 'd_id': '199'}```

This is called dict comprehension and creates a new dictionary. It is basically doing the equivalent of

def process_results(item_list, mapping):
    res = {}
    for k,v in item_list.items():
        for i in mapping:
            if k == i[1]:
                res[i[0]] = v
    return res

Iterating for each value of the obj dict, then iterate through the mapping list of tuples and if the value is the same as index[1] of the tuple then create a new key:value in the new dict.

  • Related