How to Create a Python dictionary with multiple values from a list?
<p>I have a Python list like below:</p>

<pre><code>['Phylum_C3.30', 'CDgu97FdFT6pyfQWZmquhFtiKrL1yp', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT_legend', 'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT', 'Family_E3.30', 'iKUmlH47RuphW3NbqXykn0ayizhztF', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG_legend', 'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG', 'Class_C2.60', 'D0RRB3F0dCl39KuEZNqfdD8q9jKzUu', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH_legend', 'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH']
</code></pre>

<p>I wish to have a dictionary where keys would be any element that starts with 'Pylum' or 'Class' or 'Order' or 'Family' or 'Genus' and values will all values following that element until the next element with 'Pylum' or 'Class' or 'Order' or 'Family' or 'Genus'.</p>

<p>For e.g:</p>

<p>The final dictionary will look like:</p>

<pre><code>{
    "Phylum_C3.30": [
        'CDgu97FdFT6pyfQWZmquhFtiKrL1yp',
        'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT_legend', 
        'pAnstdjgs3Dzzc8I0fOLERPeXNZIuT'
    ], 
    "Family_E3.30": [
        'iKUmlH47RuphW3NbqXykn0ayizhztF',
        'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG_legend',
        'ZzTzTLMDCHIkPBo9waDG3lBZi6u2hG'
    ],
    "Class_C2.60": [
        'D0RRB3F0dCl39KuEZNqfdD8q9jKzUu',
        'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH_legend',
        'MYe9hzd8BTeg1OW00TMQQ0qc60KWIH'
    ],
}
</code></pre>

<p>Simply loop over the list, and if a value tests as a key store that as the most 'recent' key seen, and add a list to the dictionary for that key. Then for all other non-key values add to the list associated with the last-seen key:</p>

<pre><code>prefixes = ('Pylum', 'Class', 'Order', 'Family', 'Genus')
output = {}
current_key = None
for elem in inputlist:
    if any(elem.startswith(p) for p in prefixes):
        # this is a key, add it to the output
        current_key = elem
        if current_key not in output:
            output[current_key] = []
    else:
        output[current_key].append(elem)
</code></pre>

<p>You can tweak the way a key is handled a bit; dropping the <code>if current_key not in output</code> would result in duplicate entries overwriting previous entries. Or you could raise an exception for the <code>if current_key in output</code> case if duplicate entries is supposed to be a bug.</p>

python python-2.7 dictionary