'NoneType' object has no attribute 'append'
<p>I have two lists that I'm merging into a dictionary</p>

<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>

<p>The expected output will be something like</p>

<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'groupchat_2']
}
</code></pre>

<p>My code to create the dictionary is below.</p>

<pre><code>out = {}
out = dict.fromkeys(keys)

for tests in tests_available:
    if tests.split('_')[0] in keys:
        key = tests.split('_')[0]
        out[key].append(tests)
</code></pre>

<p>However, it is throwing the error  'NoneType' object has no attribute 'append' when it is trying to append the values to the key. Can anyone help me identify what is wrong in my code?</p>

<p>If you use a defaultdict then the append call will work as the value type defaults to a list:</p>

<pre><code>In [269]:
from collections import defaultdict
keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
d = defaultdict(list)
for test in tests_available:
    k = test.split('_')[0]
    if k in keys:
        d[k].append(test)
d.items()

Out[269]:
dict_items([('p2p', ['p2p_1', 'p2p_2', 'p2p_3']), ('groupchat', ['groupchat_1', 'groupchat_2'])])
</code></pre>

<p>See the docs: <a href="https://docs.python.org/2/library/collections.html#defaultdict-examples" rel="nofollow">https://docs.python.org/2/library/collections.html#defaultdict-examples</a></p>

python