使用文件的python字典帮助

时间:2012-07-16 02:12:26

标签: python dictionary

我有一个关于在给定文件的情况下编写字典的问题。我做了编码,但我真的很困惑。参数名称为“load_words: (file)”,预期输出为“dict of {str: list of strs}”。

给出的问题的描述是:

  

“打开的文件每行包含一个小写单词。返回一个字典,其中每个键都是一个小写字母,每个值都是文件中以该字母开头的单词列表。只有一个或多个字母文件中的单词以词典中的键出现。“

我正在尝试为

编写代码
def load_words(file1):

我真的不知道如何处理这个问题,任何帮助都会得到任何提示或甚至是完整的解决方案,我可以向后工作。

注意:不是家庭作业问题。我有两天的期中考试,我正在尝试做过去的中期,所以请帮忙

2 个答案:

答案 0 :(得分:2)

只需在伪代码中写出你需要做的逻辑,然后再回过头来填写实际代码:

感谢@mhawke指出我误解了问题

function load_words(file)
  for each line in the file
    get the first letter of the line (word)
    lowercase the letter
    if dict[letter] does not yet exist
        create an empty list at this key
    add word to list in dict with first letter as key
  return the dict

答案 1 :(得分:1)

最简单的方法是使用collections.defaultdict,如下所示:

def load_words(file1):
    answer = collections.defaultdict(list)
    for line in file1:
        line = line.strip()
        if line not in answer[line[0]]:
            answer[line[0]].append(line)
    return answer

但是,对于你的期中考试,你的教授可能会期待这个答案:

def load_words(file1):
    answer = {}
    for line in file1:
        line = line.strip()
        if line[0] in answer: # or in answer.keys() or in answer.iterkeys()
            if line not in answer[line[0]]:
                answer[line[0]].append(line)
        else:
            answer[line[0]] = [line] # or answer[line[0]] = []; answer[line[0]].append(line)
    return answer

希望有所帮助