'Creating Dictionary of first letter from list of words from txt file
I have a txt file with a list of words. I want to take those words and create a dictionary with using the first letter as the key and then appending the words that start with that letter. This is what I have so far...
file = open('words.txt').read()
print(file)
the result of the file: ["aback","abaft","abandoned","abashed","aberrant","abhorrent","abiding","abject","ablaze","able","abnormal","aboard","aboriginal","abortive","abounding","abrasive","abrupt","absent","absorbed","absorbing","abstracted","absurd","abundant","abusive","acceptable","accessible", ....]
alphaDict = {}
for word in file:
if word[0] not in alphaDict.keys():
alphaDict[word[0]] = []
alphaDict[word[0]].append(word)
else:
alphaDict[word[0]].append(word)
for k,v in alphaDict.items():
print(k , ":", v)
What am I missing? This is the result I get. [ : ['['] " : ['"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"', '"',
Solution 1:[1]
Your file looks like a json file containing the list of words. You should to json.load()
to deserialize it into a python list before iterating for word in file
:
import json
with open("words.txt") as f:
words = json.load(f)
I renamed file to words, because your variable names should indicate what they are
Also, you don't need the else:
, because you want to append to the list regardless of whether it existed before this iteration or you created it in this iteration:
alphaDict = {}
for word in file:
if word[0] not in alphaDict: # In py3, don't need to do .keys()
alphaDict[word[0]] = []
alphaDict[word[0]].append(word)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pranav Hosangadi |