繁体   English   中英

Python将已排序的列表转换为具有指定为(key,value)对的Dict

[英]Python convert sorted List to Dict with position specified as (key, value) pair

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

[a0, a1, a2, a3, ..., aj, ... ]

转换为Dict数据类型,其位置如下所示:

{
    a0: {'index':0},
    a1: {'index':1},
    a2: {'index':2},
    ...
    aj: {'index':j},
    ...
}

请在这里澄清一些问题:

  • 字典中实际上有更多对,例如{'index': j, 'name': wow, ...}并从列表转换为该字典是必要的,其他属性(例如'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循环,但是没有发生

使用Dict理解 (单线;如果您没有两个关注点):

result = {key: {"index": index} for index, key in enumerate(yourList)}

您可以像这样使用它:

>>> 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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM