词典未根据完整词典进行更新,仅根据最终元素进行了更新

时间:2018-11-20 07:46:22

标签: python dictionary

我尝试构建一个类,该类可以获取文件夹总数,文件总数以及文本文件中的每个句子。

文本文件示例:

Text1.txt:

我有很多东西 我是男人 丛林之王

Text2.txt:

人类的丛林 没有丛林就没有生命 你的生活没用

我从另一个班级获得的总回报是:

总计:

[[["I have many things", "I am a man", "King of Jungle"]], [["The jungle of man", "No jungle no life", "Your life is useless"]]]

class Get(object):
    def __init__(self):
        pass

    def get_folder(self, totals=None):
        """
        Return the dictionary for sentence based on the index of folder and files
        """
        if totals is None:
            totals = self.get_files() #This is based on my another class on another file.py
        self.record = {i:{ii:totals[i][ii][iii]} for i in range(len(totals)) for ii in range(len(totals[i])) for iii in range(len(totals[i][ii]))}
        print(self.record)

我在print(self.record)时的当前输出是:

{0: {0: 'King of jungle'}, 1: {0: 'Your life is useless'}}

预期输出:

{0: {0: 'I have many things', 0: 'I am a man', 0: 'King of jungle'}, 1: {0: 'The jungle of man', 0: 'No jungle no life', 0: 'Your life is useless'}}

1 个答案:

答案 0 :(得分:0)

我不确定您的预期输出是否是正确的python字典。你能检查一下吗?另外,您还有一个字符串列表列表。是你想要的吗?

作为嵌套词典的示例,请考虑以下代码段。

values = [['a', 'b', 'c'], ['d', 'e', 'f']]
dict = {}
for i, j in enumerate(values):
    dict[i] = {}
    for k, l in enumerate(j):
        dict[i][k] = l
print(dict)
# {0: {0: 'a', 1: 'b', 2: 'c'}, 1: {0: 'd', 1: 'e', 2: 'f'}}

替代解决方案

from collections import defaultdict
values = [['a', 'b', 'c'], ['d', 'e', 'f']]
dict = {}
for i, j in enumerate(values):
    dict[str(i)] = defaultdict(list)
    for k in j:
        dict[str(i)][0].append(k)
print(dict)
# {'0': defaultdict(<class 'list'>, {0: ['a', 'b', 'c']}),
#  '1': defaultdict(<class 'list'>, {0: ['d', 'e', 'f']})}

作为字典理解

print({i: {k: l for k, l in enumerate(j)} for i, j in enumerate(values)})
# {0: {0: 'a', 1: 'b', 2: 'c'}, 1: {0: 'd', 1: 'e', 2: 'f'}}

最后一个解决方案最快。