Python 在字典中指定小写字母作为键?

Python 在字典中指定小写字母作为键?,python,dictionary,set,python-3.4,Python,Dictionary,Set,Python 3.4,我正在编写一个简单的小代码,它接受一个文本文件,并将dict中的键指定为英语字母表a-z中的每个字母,以该字母开头的每个单词都作为一个集合指定给键。我知道一定有一种更“蟒蛇式”的方法 # P8.11 : This program builds a dictionary of sets from a text file of words. # The keys are a letter, and the values are a set of words that start with that

我正在编写一个简单的小代码,它接受一个文本文件,并将dict中的键指定为英语字母表a-z中的每个字母,以该字母开头的每个单词都作为一个集合指定给键。我知道一定有一种更“蟒蛇式”的方法

# P8.11 : This program builds a dictionary of sets from a text file of words.
# The keys are a letter, and the values are a set of words that start with that
# letter.

def main():
    wordList = set()
    inFile = open("words.txt", "r")
    for line in inFile:
        line = line.rstrip()
        line = line.lower()
        wordList = line.split()
        print(buildDict(wordList))
    print(wordList)
def buildDict(wordList):
    wordDict = dict()
    for word in wordList:
        if word.startswith("a"):
            wordDict["a"] = word
        if word.startswith("b"):
            wordDict["b"] = word
        if word.startswith("c"):
            wordDict["c"] = word
        if word.startswith("d"):
            wordDict["d"] = word
        if word.startswith("e"):
            wordDict["e"] = word
        if word.startswith("f"):
            wordDict["f"] = word
        if word.startswith("g"):
            wordDict["g"] = word
        if word.startswith("h"):
            wordDict["h"] = word
        if word.startswith("i"):
            wordDict["i"] = word

    return wordDict

您只需要从
word
中提取第一个字母,并将其用作键
setdefault
确保如果
word\u dict[word[0]]
尚不存在,则将其添加为键

for word in word_list:
    word_dict.setdefault(word[0], set()).add(word)
您还可以使用
defaultdict

import collections

word_dict = collections.defaultdict(set)
for word in word_list:
    word_dict[word[0]].add(set0)
最后,使用
itertools
operator
模块的一行程序(分成多行以便于阅读)
groupby
负责按单词的第一个字母对单词进行分组
itemgetter
只是另一种编写
lambda x:x[0]


肯定有一种更像蟒蛇的方式:

from collections import defaultdict

word_dict = defaultdict(set)

with open('words.txt') as f:
     for word in f:
         word_dict[word[0]].add(word)

print(word_dict)

考虑使用单词的第一个字符,而不是startswith

from collections import defaultdict   
def buildDict(wordList):
     wordDict=defaulttict(set)
     for word in wordList:
          wordDict[word[0]].add(word)

这与我在回答中发布的内容是一样的。我开始回答这个问题,因为对于伟大的重构,+1附近没有任何答案-不过你可能想再次保护零长度单词。:)@MariaZverina这是一个好主意,但我认为假设正确的输入可能是可以的,这样可以保持答案简洁,与问题相关。
from collections import defaultdict   
def buildDict(wordList):
     wordDict=defaulttict(set)
     for word in wordList:
          wordDict[word[0]].add(word)