【问题标题】:Create a Dictionary of Dictionary from a Tuple of Dictionary Inside a List从列表中的字典元组创建字典字典
【发布时间】:2018-11-13 00:37:28
【问题描述】:

我有一个这样的元组,

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]}}

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

【问题讨论】:

    标签: python list dictionary tuples


    【解决方案1】:

    您可能不需要在此处创建临时列表或字典,因为您可以从 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)
    

    【讨论】:

    • "The key here is that your initial tuple contains lists which have a similar structure, so in your code, the structure of your final dictionary is already determined after the first iteration of the first for loop" 这是我遇到问题的地方,我一直在尝试一步一步,在我的第二次迭代中 output_1 被替换。 defaultdict是解决这个问题的唯一方法吗?
    • 你现在在我眼里就像神一样!感谢您展示两种方式,我应该学习defaultdictionaries。老实说,我不知道python中有这样的东西!
    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2011-08-29
    • 2019-01-16
    相关资源
    最近更新 更多