我有一个嵌套列表,我想根据嵌套列表中的特定值将其拆分并排序到字典中。
这是示例代码:
list = [['item1',['some_value1', 1]], [['item2',['some_value2', 2]], ['item3',['some_value3', 1]]]
# I would like to convert this list into a dictionary
final_dict1 = {1:{'item1':['some_value1', 1], 'item3':['some_value3', 1]}, 2:{'item2':['some_value2', 2]}}
# OR
final_dict2 = {1:[['item1',['some_value1', 1]], ['item3',['some_value3', 1]]], 2:['item2':['some_value2', 2]]}
基本上,我想根据列表项在各自子列表中的排序方式,并根据其创建字典。
答案 0 :(得分:1)
IIUC,您可以执行以下操作(使用collections.defaultdict):
from collections import defaultdict
lst = [['item1',['some_value1', 1]], ['item2',['some_value2', 2]], ['item3',['some_value3', 1]]]
result = defaultdict(dict)
for i, (val, idx) in lst:
result[idx][i] = [val, idx]
print(dict(result))
输出
{1: {'item1': ['some_value1', 1], 'item3': ['some_value3', 1]}, 2: {'item2': ['some_value2', 2]}}
答案 1 :(得分:0)
list = [['item1',[someValue1, 1]], ['item2',[someValue2, 2]], ['item3',[someValue3, 1]]]
result = {}
for i, item in enumerate(list):
result[i] = {item[1][0]: item[1][1]}