2013-03-25 2323 views
0

因此,我正在编写一个程序,该程序从字文件读取并打印出一组字作为字母。在python中使用元组作为字典中的字典键

目前,我有一个函数,它接受一个字符串,并返回一个元组,并将所有字母全部整理出来。

def getLetters(string): 
    """Purpose, to nab letters from a string and to put them in a tuple in 
    sorted order.""" 
    tuple_o_letters = sorted(tuple(string)) 
    if _DEBUG: 
     print tuple_o_letters 

    return tuple_o_letters 

发送到这个函数是这个代码

try: 
    fin = open("words.txt") 
except: 
    print("no, no, file no here.") 
    sys.exit(0) 

wordList = [] 
for eachline in fin: 
    wordList.append(eachline.strip()) 
for eachWord in wordList: 
    getLetters(eachWord) 

现在,虽然我可以很容易地使元组,在那里我坚持是我想这些存储作为字典键,这将是最佳因为元组和键是不可变的,但我对这样做的方法感到困惑。此外,这些值将是这些键的单词列表。

+0

'字典= {}' '的eachWord在单词表:' '元组= getLetters(eachWord)' '的eachTuple在元组:' '字典=(eachTuple,单词表)' '打印字典' – user1768884 2013-03-25 17:00:07

+1

如何使用'dict [key] = value'? – 2013-03-25 17:00:14

+1

但是不要*使用'tuple'和'dict'作为变量名称,隐藏内置类型。 – 2013-03-25 17:02:41

回答

3

sorted()返回一个列表,你想交换你行:

tuple_o_letters = tuple(sorted(string)) 

这种种在string的字母,然后转动所产生的排序列表到一个元组。