Not sure if i am using dictionaries properly | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Not sure if i am using dictionaries properly

I was trying to create a text analyzer with both dictionary and string formatting, but i seem to have gotten an error at the second last statement. It says: line 25 in <module> msg = ("{0} = {1}%".format(letters, dict(letters))) ValueError: dictionary update sequence element #0 has length 1; 2 is required. How do i solve this: #text analyzer #starting of the program textfile = input("Enter text document:") with open(textfile) as f: text = f.read() print(text) def count_char(text, char): count = 0 dict = {} for c in text: if c == char: count += 1 dict[char] = count*100/len(text) characters = ["abcdefghijklmnopqrstuvwxyz"] text = text.lower() for letters in characters: count_char(text, str(letters)) msg = ("{0} = {1}%".format(letters, dict(letters))) print(msg) EDIT: text = "Pretend that this is text in a file" print(text) def count_char(text, char): count = 0 dict = {} for c in text: if c == char: count += 1 dict[char] = count*100/len(text) characters = ["abcdefghijklmnopqrstuvwxyz"] text = text.lower() for letters in characters: count_char(text, str(letters)) msg = ('{0} = {1}%'.format(letters, dict[letters]))

12th Jun 2017, 3:26 PM
Nicholas Hay
Nicholas Hay - avatar
3 Answers
+ 3
# There are several mistakes: # in count_char() function, don't use a local dict if you want to access it from outside (your latest letters loop)... # rather than handle a global var, let it return the count: def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count*100/len(text) # definition of list of char doesn't need to be written inside squared brackets, as string are already a kind of list: characters = "abcdefghijklmnopqrstuvwxyz" # else you later iterate over the unque string in the list ^^ text = text.lower() for letters in characters: c = count_char(text, letters) # no need for str(), as letters is already of string type (once char string) msg = "{0} = {1}%".format(letters, c) # use the returned value of count_char() rather than trying to use a bad used dict ;) print(msg)
12th Jun 2017, 3:50 PM
visph
visph - avatar
+ 2
Dont use dict(letters), but dict[letters] (squared brackets, not rounded ones are used to access a key-index value)... By the way, I cannot run your code, as you use external file(s) ^^
11th Jun 2017, 6:42 AM
visph
visph - avatar
0
When i tried that out, i got a different error: "TypeError: 'type' object is not subscriptable" I don't understand what i am doing wrong I just edited the code, to run without external files.
12th Jun 2017, 3:25 PM
Nicholas Hay
Nicholas Hay - avatar