将字典键重新映射到 python 中的另一个字典键时出错

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

下面是我的代码:

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 输出:

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

我得到的错误:

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

任何人都可以建议实现 desired/wanted 输出的正确方法 我还是 python 的新手,为 mistakes/errors 道歉,或者如果我的代码听起来像 silly/dumb ;-) 给你

您可以这样做,尽管从技术上讲您的 mapping_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]}

这会给

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

这称为字典理解并创建一个新字典。 它基本上相当于

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

遍历 obj 字典的每个值,然后遍历 mapping 元组列表,如果该值与元组的索引 [1] 相同,则创建一个新的 key:value 在新字典中。