从嵌套列表创建嵌套字典

时间:2019-07-27 16:35:12

标签: python

如何使用python将嵌套列表的列表转换为嵌套字典?

students = [[1, 'John', 'Smith'], [2, 'Anna', 'Jones']]

students_dict = {'1': {'name': 'John', 'surname': 'Smith'},
             '2': {'name': 'Anna', 'surname': 'Jones'}}

2 个答案:

答案 0 :(得分:2)

您可以使用打开包装:

students = [[1, 'John', 'Smith'], [2, 'Anna', 'Jones']]
result = {a:dict(zip(['name', 'surname'], b)) for a, *b in students}

输出:

{1: {'name': 'John', 'surname': 'Smith'}, 2: {'name': 'Anna', 'surname': 'Jones'}}

答案 1 :(得分:0)

您的子词典关键字是:

students_dict = {d[0] : dict(zip(keys, d[1:])) for d in students}

通过将键和值(在第一个元素之后)压缩在一起来创建子词典,然后将第一个元素作为键添加到外部字典中:

import tkinter as tk
from tkinter import filedialog
file_path = filedialog.askopenfilename()
print(file_path)
data =  []
data2 = []
data3 = []
flag= False
    with open(file_path,'r') as f:
    for line in f:
        if line.strip().startswith('*NSET, NSET=Nodes_Pushed_Back_IB'):
            flag= True
        elif line.strip().endswith('*NSET, NSET=Nodes_Pushed_Back_OB'):
            flag= False    
        elif flag:          # as long as flag is true append
            data.append(int(line).strip())