Python将排序列表转换为Dict,位置指定为(键,值)对

Python将排序列表转换为Dict,位置指定为(键,值)对,python,dictionary,data-structures,Python,Dictionary,Data Structures,Python新手,转换排序列表的最佳方法是什么(是的,列表中的元素是唯一的): 指向位置如下所示的Dict数据类型: { a0: {'index':0}, a1: {'index':1}, a2: {'index':2}, ... aj: {'index':j}, ... } 请在此澄清一些担忧: 实际上,dict中有更多的对,例如{'index':j,'name':wow,},并且需要将列表转换为这样的dict,其他属性,例如'name'将添

Python新手,转换排序列表的最佳方法是什么(是的,列表中的元素是唯一的):

指向位置如下所示的Dict数据类型:

{
    a0: {'index':0},
    a1: {'index':1},
    a2: {'index':2},
    ...
    aj: {'index':j},
    ...
}
请在此澄清一些担忧:

  • 实际上,dict中有更多的对,例如
    {'index':j,'name':wow,}
    ,并且需要将列表转换为这样的dict,其他属性,例如
    'name'
    将添加到创建dict后的,因此基本上看起来如下所示,首先创建dict,第二,基于键
    aj
    添加其他属性,其他属性随后出现
  • 显式定义
    索引
    是必要的,它最终看起来像:
    {'index':myFunc(j)}
非常感谢你的帮助


我所尝试的:

  • 尝试了
    l=zip(mylist,range(len(mylist))
    并将
    l
    (看起来像
    [(a0,0),(a1,1),…])
    转换为dict,但是,它的列表中包含
    元组
  • 尝试了
    d=dict(zip(mylist,range(mylist.len))
    ,但仍然需要将
    {ai:i}
    转换为
    {ai:{'index':i}}
    ,不知道从这里解决问题的绝妙方法
  • 尝试了朴素的
    循环,但没有成功
  • 使用(一行;如果您没有这两个问题):

    您可以像这样使用它:

    >>> yourList = range(10)
    >>> result = {key: {"index": index} for index, key in enumerate(yourList)}
    >>> result
    {0: {'index': 0}, 1: {'index': 1}, 2: {'index': 2}, 3: {'index': 3}, 4: {'index': 4}, 5: {'index': 5}, 6: {'index': 6}, 7: {'index': 7}, 8: {'index': 8}, 9: {'index': 9}}
    
    对于解释这两个项目的解决方案,我建议如下:

    result = {}
    for index, item in enumerate(yourList):
        currentDict = {"name": "wow", .. all your other properties .. }
        currentDict["index"] = index #Or may be myFunc(index)
        result[item] = currentDict
    
    注意:我希望您在原始列表中使用可哈希项。

    使用(一行;如果您没有这两个问题):

    您可以像这样使用它:

    >>> yourList = range(10)
    >>> result = {key: {"index": index} for index, key in enumerate(yourList)}
    >>> result
    {0: {'index': 0}, 1: {'index': 1}, 2: {'index': 2}, 3: {'index': 3}, 4: {'index': 4}, 5: {'index': 5}, 6: {'index': 6}, 7: {'index': 7}, 8: {'index': 8}, 9: {'index': 9}}
    
    对于解释这两个项目的解决方案,我建议如下:

    result = {}
    for index, item in enumerate(yourList):
        currentDict = {"name": "wow", .. all your other properties .. }
        currentDict["index"] = index #Or may be myFunc(index)
        result[item] = currentDict
    

    注意:我希望您在原始列表中使用可散列项。

    您的列表元素唯一吗?
    'name':哇,
    从何而来?这里有一个提示:我修改了,谢谢指出,@Saicharan s MI修改了,谢谢指出,@alfasin您的列表元素唯一吗?
    'name':哇,…
    来自哪里?这里有一个提示:我修改了,谢谢你的指点,@Saicharan s MI modified,谢谢你的指点,@alfasin请允许我稍后尝试你的答案,我会回复你的。谢谢你的帮助。请允许我稍后尝试你的答案,我会回复你的。谢谢你的帮助。