2012-07-16 66 views
0

我有一个关于给文件编写字典的问题。我已经完成了编码,但是我很困惑。参数名称为“load_words: (file)”,预期输出为“dict of {str: list of strs}”。使用文件python的字典帮助

给出的问题的描述是:

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

我想写我的代码为

def load_words(file1): 

我真的不知道如何处理这个问题任何帮助将不胜感激任何提示,甚至一个完整的解决方案,我可以倒退。

注意:不是一个家庭问题。我有2天的中期,我试图做过去的期中考试,所以请帮助

回答

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 

希望帮助

+1

我想,当你正在学习的基础知识不使用defaultdict建议。您正在避免如何检查密钥 – jdi 2012-07-16 02:20:07

+0

的字典的概念。我已经添加了第二个解决方案。 – inspectorG4dget 2012-07-16 02:22:06

+0

这只是一个如何正确使用字典和列表值的例子?它不是解决实际问题的办法。 – jdi 2012-07-16 02:22:47

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