'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>Your values are set to <em>None</em> in <em>fromkeys</em> unless you explicitly set a value:</p>

<p><strong>fromkeys(seq[, value])</strong></p>

<p><em>Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.</em></p>

<p>In your case you need to create lists as values for each key:</p>

<pre><code>d = {k:[] for k in keys}
</code></pre>

<p>You can also do your if check using the dict:</p>

<pre><code>d = {k:[] for k in keys}

for test in tests_available:
    k = tests.split('_', 1)[0]
    if k in d:
        d[k].append(test)
</code></pre>

<p>You can pass a value to use to <em>fromkeys</em> but it has to be <em>immutable</em> or you will be sharing the same object among all keys.</p>

python