+ 2

Function returning a dictionary with string lengths (keys) and number of occurrence (values) from a list

I am trying to write a function that takes a list of strings and returns a dictionary where the keys represent a length and the values represent how many strings have that length in the list. This is what I have written and my output: def length_counts(stringList): stringDict = {} for value in stringList: stringDict[len(value)] = stringList.count(value) return stringDict #test sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"] print(length_counts(sa_countries)) #output {6: 1, 9: 1, 7: 1, 4: 1} Correct output should be: {6: 1, 9: 2, 7: 2, 4: 1} Which says there is 1 string with 6 letters, 2 strings with 9 letters, 2 strings with 7 letters, and 1 string with 4 letters. Thank you.

13th Apr 2020, 1:15 PM
hartechworld
hartechworld - avatar
7 Respostas
+ 7
This a solution using comprehensions: sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"] lens = [len(i) for i in sa_countries] print(*[{x:lens.count(x)} for x in set(lens)]) # output: {9: 2} {4: 1} {6: 1} {7: 2}
13th Apr 2020, 4:14 PM
Lothar
Lothar - avatar
+ 6
Here is also a version with for loops: def length_counts(stringList): stringDict = {} lens = [] res = {} for i in stringList: lens.append(len(i)) for j in set(lens): res.update({j:lens.count(j)}) return res sa_countries = ["Brazil", "Venezuela", "Argentina", "Ecuador", "Bolivia", "Peru"] print(length_counts(sa_countries))
13th Apr 2020, 6:08 PM
Lothar
Lothar - avatar
+ 3
You can obtain a previous count for a specified length and increment it. https://code.sololearn.com/cn1Kd6Kee2O4/?ref=app
13th Apr 2020, 2:18 PM
Ipang
+ 2
stringList.count(value) will only return how many times a country is repeated in the string list.
13th Apr 2020, 1:29 PM
Bahhaⵣ
Bahhaⵣ - avatar
13th Apr 2020, 1:38 PM
Bahhaⵣ
Bahhaⵣ - avatar
+ 2
Thanks @Bahha
13th Apr 2020, 2:08 PM
hartechworld
hartechworld - avatar
+ 2
Lothar thank you
14th Apr 2020, 7:01 AM
hartechworld
hartechworld - avatar