【发布时间】:2013-03-25 17:51:04
【问题描述】:
所以我有一个程序,它接受一个字符串,并返回一个元组,其中字符串中的所有字母按排序顺序。
然后程序需要创建一个字典,以元组作为键,值是所有带有键的单词的列表
到目前为止,我有:
_DEBUG = True
def getLetters(string):
"""Purpose, to nab letters from a string and to put them in a tuple in
sorted order."""
#sort the letters and put them in a tuple
tuple_o_letters = tuple(sorted(string))
if _DEBUG:
print tuple_o_letters
return tuple_o_letters
def main():
try:# open the file
fin = open("words2.txt")
except:
#if file doesn't exist
print("no, no, file no here.")
sys.exit(0)
wordList = [] #create a word list
for eachline in fin:
#fill up the word list and get rid of new lines
wordList.append(eachline.strip())
word_dict = {} # create a dictionary
for eachWord in wordList:
tuple = getLetters(eachWord) # make a tuple out of each word
word_dict[tuple] = wordList #store it into a dictionary
print word_dict #print out the dictionary
if __name__ == '__main__':
main()
现在,虽然我可以将元组存储为字典键,但我不知道当且仅当单词列表具有这些键时,如何将单词列表存储为值。
例如: 如果在字典中如果有键 ('d', 'o', 'g'),我会得到该特定条目的值 god 和 dog,假设这两个单词在单词列表中(从words2.txt 文件。
【问题讨论】:
标签: python dictionary tuples