[英]key value pair position change when converting sorted ordereddict to 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)}
。 非常感謝您的幫助!
我嘗試過的
l = zip(mylist, range(len(mylist)))
並將l
(看起來像[(a0, 0), (a1, 1), ...]
)轉換為dict,但是,它的列表里面有tuple
; d = dict(zip(mylist, range(mylist.len)))
但仍然需要將{ai: i}
轉換為{ai:{'index': i}}
並且不知道從這里解決的絕妙方法; 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.