首页 > 解决方案 > 如何将项目列表翻译成字典列表,其中项目作为字典元素

问题描述

我在python中有以下列表:

napps_list= ['84:kytos/kytos',
             '85:kytos/python-openflow',
             '88:kytos/of_core',
             '101:kytos/kytos-utils',
             '90:kytos/mef_eline',
             '91:kytos/flow_manager',
             '92:kytos/topology',
             '93:kytos/kronos',
             '94:kytos/pathfinder',
             '95:kytos/status',
             '96:kytos/of_l2ls',
             '97:kytos/of_lldp',
             '103:kytos/maintenance',
             '99:kytos/storehouse',
             '107:kytos/kytos-end-to-end-tester']

我正在尝试将其转换为以下格式的字典列表:

 {
    "data": [
          {
              "{#NAPP}": "kytos/mef_eline",
          },
          {
              "{#NAPP}": "kytos/pathfinder",
          },
          {
              "{#NAPP}": "kytos/topology",
          }
    ]
}

到目前为止,我有:

content = dict() 
content["data"] = [] 
content["data"]["#NAPP"] = dict()

但是我无法让所有条目都具有相同的键#NAPP,但元素不同......

标签: pythondictionary

解决方案


out = {"data": [{"{#NAPP}": i.split(":")[-1]} for i in napps_list]}

from pprint import pprint    
pprint(out)

印刷:

{'data': [{'{#NAPP}': 'kytos/kytos'},
          {'{#NAPP}': 'kytos/python-openflow'},
          {'{#NAPP}': 'kytos/of_core'},
          {'{#NAPP}': 'kytos/kytos-utils'},
          {'{#NAPP}': 'kytos/mef_eline'},
          {'{#NAPP}': 'kytos/flow_manager'},
          {'{#NAPP}': 'kytos/topology'},
          {'{#NAPP}': 'kytos/kronos'},
          {'{#NAPP}': 'kytos/pathfinder'},
          {'{#NAPP}': 'kytos/status'},
          {'{#NAPP}': 'kytos/of_l2ls'},
          {'{#NAPP}': 'kytos/of_lldp'},
          {'{#NAPP}': 'kytos/maintenance'},
          {'{#NAPP}': 'kytos/storehouse'},
          {'{#NAPP}': 'kytos/kytos-end-to-end-tester'}]}

推荐阅读