Alright well I am trying to create a dictionary from a text file so the key is a single lowercase character and each value is a list of the words from the file that start with that letter.
The text file containts one lowercase word per line eg:
airport
bathroom
boss
bottle
elephant
Output:
words = {'a': ['airport'], 'b': ['bathroom', 'boss', 'bottle'], 'e':['elephant']}
Havent got alot done really, just confused how I would get the first index from each line and set it as the key and append the values. would really appreatiate if someone can help me get sarted.
words = {}
for line in infile:
line = line.strip() # not sure if this line is correct
So let’s examine your example:
This looks good for a beginning. Now you want to do something with the
line. Probably you’ll need the first character, which you can access throughline[0]:Then you want to check whether the letter is already in the dict. If not, you can add a new, empty list:
Then you can append the word to that list:
And you’re done!
If the lines are already sorted like in your example file, you can also make use of
itertools.groupby, which is a bit more sophisticated:You can also sort the lines first, which makes this method generally applicable: