首页 > 解决方案 > 从列表中的字典元组创建字典字典

问题描述

我有一个这样的元组,

sample_tuple = ([{1:["hello"], 2: ["this"], 3:["is fun"]},{1:["hi"], 2:["how are you"]}],
                [{1: ["this"], 2:[], 3:["that"]}, {1:[], 2:["yes"]}])

从这个元组,我想创建一个字典,它的键值作为字典。

步骤1:

迭代主要的大元组并跟踪列表的索引。

第2步:

进入元组内的列表并跟踪这些大列表的索引。

即,0第一个列表的索引,

[{1:["hello"], 2: ["this"], 3:["is fun"]},{1:["hi"], 2:["how are you"]}] 

第 3 步:

我想遍历列表中字典的键和值。

即第一本词典

{1:["hello"], 2: ["this"], 3:["is fun"]}

第 4 步: 在遍历字典值时,我要检查并确保值不为空且不为 None。

当这个过程发生时,我想创建一个字典。为此dictionary

KEY:(step 2大列表中每个字典的每个索引)的索引。

VALUES:如果字典的值不为空,则字典的键来自step 3的键(来自我上面的字典)和值作为(棘手的部分)列表。step 3正如您在下面看到的,我有一个空列表temporary_keyword_list,应该将非空列表值保存到一个临时列表中,但我没有得到我想要的。

以下是我尝试过的、得到的以及我想要的输出。

output_1 = {}
for index, each_keyword in enumerate(sample_tuple):

    for ind, each_file in enumerate(each_keyword):
        temporary_dict = {}

        for key, value in each_file.items():

            temporary_keyword_list = []
            # Check if a value is not empty or not None
            if value!= [] and value is not None:
                temporary_keyword_list.append(index) ## Here I want to save the index (tricky part)

            # Start inserting values into the dictionary. 
            temporary_dict[key] = temporary_keyword_list

        # Final big dictionary 
        output_1[ind] = temporary_dict  

我现在的output_1字典:

{0: {1: [1], 2: [], 3: [1]}, 1: {1: [], 2: [1]}}

期望的输出:

{0: {1: [0, 1], 2: [0], 3: [0, 1]}, 1: {1: [0], 2: [0, 1]}}

由于它的元组、列表和字典,我尽力解释我遇到的问题。如果这没有意义,请在评论中告诉我,我会尽力解释。任何帮助或建议都会很棒。

标签: pythonlistdictionarytuples

解决方案


您可能不需要在此处创建临时列表或字典,因为您可以从 for 循环中获取所需的所有索引。这里的关键是您的初始元组包含具有相似结构的列表,因此在您的代码中,最终字典的结构已经在第一个 for 循环的第一次迭代之后确定。当您计划在其中存储列表时,请考虑在创建内部字典时使用 defaultdict。然后就是正确处理索引和值。下面的代码应该可以工作。

from collections import defaultdict
sample_tuple = ([{1: ["hello"], 2: ["this"], 3: ["is fun"]},
                 {1: ["hi"], 2: ["how are you"]}],
                [{1: ["this"], 2: [], 3: ["that"]}, {1: [], 2: ["yes"]}])
output_1 = {}
for index, each_keyword in enumerate(sample_tuple):
    for ind, each_file in enumerate(each_keyword):
        if index == 0:
            output_1[ind] = defaultdict(list)
        for key, value in each_file.items():
            if value != [] and value is not None:
                output_1[ind][key].append(index)
            print(output_1)

要回答您的评论,您可以在没有 defaultdict 的情况下进行管理,但您真的想这样做吗?

sample_tuple = ([{1: ["hello"], 2: ["this"], 3: ["is fun"]},
                 {1: ["hi"], 2: ["how are you"]}],
                [{1: ["this"], 2: [], 3: ["that"]}, {1: [], 2: ["yes"]}])
output_1 = {}
for index, each_keyword in enumerate(sample_tuple):
    for ind, each_file in enumerate(each_keyword):
        for key, value in each_file.items():
            if index == 0:
                if key == 1:
                    if value != [] and value is not None:
                        output_1[ind] = {key: [index]}
                else:
                    if value != [] and value is not None:
                        output_1[ind][key] = [index]
            else:
                if value != [] and value is not None:
                    output_1[ind][key].append(index)
            print(output_1)

推荐阅读