I think I have the right idea on how to solve this function, but I'm not sure why I don't get the desired results shown in the docstring. Can anyone please help me fix this?
def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
count = count + length
d[length] = {count}
count += 1
return d
Using Counter
definitely is the best option:
In [ ]: from collections import Counter
...: d = Counter(map(len, s))
...: d == {1:2, 6:2, 8:1, 2:1, 10:1}
Out[ ]: True
Without using "fancy stuff", we use generator expressions, something I consider to be equally fancy:
Counter(len(i) for i in s)
If by "ordinarily" you mean using for loops, we can do that like so:
d = {}
for i in s:
if len(i) not in d:
d[len(i)] = 1
else:
d[len(i)] += 1
Simply do a loop for any word in the list. In each iteration create new key with value 1
if the length is not in the dict as a key yet, otherwise increase the previous value for the key:
def list_to_dict(word_list):
d = dict()
for any_word in word_list:
length = len(any_word)
if length not in d:
d[length] = 1
else:
d[length] += 1
return d
You can use dictionary comprehension to iterate over s
, which now contains the length of its original elements:
s = ['A', 'little', 'sentence', 'to', 'create', 'a', 'dictionary']
final_s = {i:len([b for b in s if len(b) == i]) for i in map(len, s)}
Output:
{1: 2, 6: 2, 8: 1, 2: 1, 10: 1}
Simply:
new_d = {}
for i in s:
new_d[len(i)] = 0
for i in s:
new_d[len(i)] += 1
Output:
{8: 1, 1: 2, 2: 1, 10: 1, 6: 2}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.