首页 > 解决方案 > 您如何将文件读入字典,其键为单词长度,值作为具有该长度的单词

问题描述

对于我的代码,我需要读取一个文件并将其放入带有列表的字典中。例如,如果 file.txt 包含:

cat
dog
as
mars
hello

我需要将其格式化为{2 : ["as"], 3 : ["cat", "dog"], 4 : ["mars"], 5 : ["hello"]}

这是我迄今为止尝试过的

dictionary = {}
file = open(dictionary_file, "r")
for line in file:
    x = line
    b = len(line)-1
    x = line[0:b]
    dictionary[b].append(x)

标签: pythonpython-3.x

解决方案


d = {}
with open('data.txt', 'r') as fp:
    for line in fp.readlines():
        line = line.strip()
        if not line:
            continue
        key = len(line)
        if not key in d:
            d[key] = []
        d[key].append(line)
print(sorted(d.items(), key=lambda item:item[0]))

推荐阅读