Python将排序后的List转换为Dict,其位置指定为(键,值)对

use*_*318 0 python dictionary data-structures

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

[a0, a1, a2, a3, ..., aj, ... ]
Run Code Online (Sandbox Code Playgroud)

到Dict数据类型,其位置如下所示:

{
    a0: {'index':0},
    a1: {'index':1},
    a2: {'index':2},
    ...
    aj: {'index':j},
    ...
}
Run Code Online (Sandbox Code Playgroud)

请在此澄清一些问题:

  • 在dict中实际上有更多的对{'index': j, 'name': wow, ...}并且从列表转换为这样的dict是必要的,其他属性,比如'name'将在dict创建之后添加,所以基本上它看起来像下面,首先创建dict,然后第二个在aj添加其他属性的键上,其他属性稍后出现;
  • 明确定义index是必要的,它最终将如下所示:{'index': myFunc(j)}.

非常感谢您的帮助!


我尝试过的:

  1. 尝试l = zip(mylist, range(len(mylist)))并转换l(看起来像[(a0, 0), (a1, 1), ...])dict,然而,它是tuple内部的列表;
  2. 尝试d = dict(zip(mylist, range(mylist.len)))但仍然需要转换{ai: i}{ai:{'index': i}}并且不知道从这里解决的好方法;
  3. 尝试过天真的for循环,但不会发生

Ult*_*nct 5

使用Dict理解(单行;如果你没有这两个问题):

result = {key: {"index": index} for index, key in enumerate(yourList)}
Run Code Online (Sandbox Code Playgroud)

您可以像以下一样使用它:

>>> 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}}
Run Code Online (Sandbox Code Playgroud)

对于解释这两个子弹的解决方案,我建议如下:

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
Run Code Online (Sandbox Code Playgroud)

注意:我希望您在原始列表中使用可清洗项目.