gpt4 book ai didi

python - 嵌套列表到嵌套字典

转载 作者:太空狗 更新时间:2023-10-30 01:57:30 24 4
gpt4 key购买 nike

我有一个包含主键的列表和一个列表列表的列表,其中每个封闭列表的第一个值(如 'key_01')应是相应值的子键(像 'val_01', 'val_02')。数据显示在这里:

master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]

我希望将这些列表组合成字典的字典,如下所示:

master_dic = {
"Master_01": {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
"Master_02": {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
"Master_03": {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}

到目前为止我得到的是子字典:

import itertools

master_dic = {}
servant_dic = {}
keys = []
values = []
for line in data_long:
for item in line:
keys.extend(item[:1])
values.append(item[1:])
servant_dic = dict(itertools.izip(keys, values))

如预期的那样,它会输出字典。

servant_dic = {
'key_06': ['val_11','val_12'], 'key_04': ['val_08','val_07'], 'key_05': ['val_09','val_10'],
'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06'], 'key_01': ['val_01','val_02']
}

问题是,如果我想将 master_keys 添加到这个字典中,以便得到想要的结果,我必须按特定顺序执行此操作,如果每一行都有一个计数器,那么这是可能的这个:

enumerated_dic =
{
0: {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
1: {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
2: {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}

我很想用 enumerate() 来做到这一点,而 servant_dic 的每一行都是构建的,但不知道如何构建。从那以后,我可以简单地将计数器 0、1、2 等替换为 master_keys

感谢您的帮助。

最佳答案

master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]


_dict = {}

for master_key, item in zip(master_keys, data_long):
_dict[master_key] = {x[0]: x[1:] for x in item}

print _dict

关于python - 嵌套列表到嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39251223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com