【发布时间】: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