Creating a dictionary where the key is an integer and the value is the length of a random sentence
<p>Super new to to python here, I've been struggling with this code for a while now. Basically the function returns a dictionary with the integers as keys and the values are all the words where the length of the word corresponds with each key.</p>

<p>So far I'm able to create a dictionary where the values are the total number of each word but not the actual words themselves.</p>

<p>So passing the following text</p>

<pre><code>"the faith that he had had had had an affect on his life"
</code></pre>

<p>to the function</p>

<pre><code>def get_word_len_dict(text):
    result_dict = {'1':0, '2':0, '3':0, '4':0, '5':0, '6' :0}
    for word in text.split():
        if str(len(word)) in result_dict:
            result_dict[str(len(word))] += 1
    return result_dict
</code></pre>

<p>returns</p>

<pre class="lang-none prettyprint-override"><code>1 - 0
2 - 3
3 - 6
4 - 2
5 - 1
6 - 1
</code></pre>

<p>Where I need the output to be:</p>

<pre class="lang-none prettyprint-override"><code>2 - ['an', 'he', 'on']
3 - ['had', 'his', 'the']
4 - ['life', 'that']
5 - ['faith']
6 - ['affect']
</code></pre>

<p>I think I need to have to return the values as a list. But I'm not sure how to approach it.</p>

<p>the problem here is you are <em>counting</em> the word by length, instead you want to <em>group</em> them. You can achieve this by storing a list instead of a int:</p>

<pre><code>def get_word_len_dict(text):
    result_dict = {}
    for word in text.split():
        if len(word) in result_dict:
            result_dict[len(word)].add(word)
        else:
            result_dict[len(word)] = {word} #using a set instead of list to avoid duplicates
    return result_dict
</code></pre>

<p>Other improvements:</p>

<ul>
<li>don't hardcode the key in the initialized <code>dict</code> but let it empty instead. Let the code add the new keys dynamically when necessary</li>
<li>you can use <code>int</code> as keys instead of strings, it will save you the conversion</li>
<li>use <code>set</code>s to avoid repetitions</li>
</ul>

<hr>

<h2>Using <code>groupby</code></h2>

<p>Well, I'll try to propose something different: you can group by length using <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>groupby</code></a> from the python standard library</p>

<pre><code>import itertools
def get_word_len_dict(text):
    # split and group by length (you get a list if tuple(key, list of values)
    groups = itertools.groupby(sorted(text.split(), key=lambda x: len(x)), lambda x: len(x))
    # convert to a dictionary with sets 
    return {l: set(words) for l, words in groups}
</code></pre>

python list python-3.x dictionary