Reputation: 59
What below gives me is an alphabetical list of my keys and values in the correct format, but is there a way to iterate the alphabetized keys and values into a list variable and print the list out so that the output looks exactly the same as the output give below? I have reviewed some similar questions; I am still left unsure if sort() actually creates a list variable that can be manipulated further down the line if I wanted.
def readFile(fileName):
fileIn = open(fileName, "r")
letterFrequency = {}
for line in fileIn:
line = line.strip()
for letter in line:
if letter.isalpha() is True:
if letter not in letterFrequency:
letterFrequency[letter.lower()] = 1
else:
letterFrequency[letter.lower()] += 1
else:
pass
fileIn.close()
return letterFrequency
def main():
fileName = input("What is the name of the file? ")
letterDict = readFile(fileName)
for letter in sorted(letterDict):
print(letter, letterDict[letter])
main()
OUTPUT FOR ABOVE:
a 102
b 11
c 31
d 58
e 165
f 27
g 2
h 80
i 17
k 3
l 42
m 13
n 63
o 93
p 15
q 1
r 79
s 44
t 60
u 21
v 24
w 21
y 10
Upvotes: 1
Views: 111
Reputation: 4849
d = {"a": 5, "n": 2, "z": 1, "c": 3, "b": 0}
t = tuple((k, d[k]) for k in sorted(d.keys()))
print(t)
# (('a', 5), ('b', 0), ('c', 3), ('n', 2), ('z', 1))
Note that you don't need the tuple()
call here; without it you'll get a (more efficient) generator. It's there in this example to make it easy to see the result.
Upvotes: 1
Reputation: 59
I have created a list, sorted the list, and printed from the dictionary, pulling the key names from the sorted list. Now, with respect to efficiency, necessity, etc.--that is beyond my scope of knowledge.
This is how I resolved my question:
def readFile(fileName):
fileIn = open(fileName, "r")
letterFrequency = {}
for line in fileIn:
line = line.strip()
for letter in line:
if letter.isalpha() == True:
if letter.lower() not in letterFrequency:
letterFrequency[letter.lower()] = 1
else:
letterFrequency[letter.lower()] += 1
else:
pass
fileIn.close()
return letterFrequency
def sortKeys(dictionary):
listNew = list(dictionary)
listNew.sort()
return listNew
def main():
fileName = input("What is the name of the file you are trying to process? ")
letterDict = readFile(fileName)
listNew = sortKeys(letterDict)
for key in listNew:
print(key, letterDict[key])
main()
Upvotes: 0