How can I only parse/split this list with multiple colons in each element? Create dictionary
<p>I have the following Python list:</p>

<pre><code>list1 = ['EW:G:B&lt;&lt;LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A&lt;F&lt;AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EY:EE:KJERWEWERKJWE']
</code></pre>

<p>I would like to take the entries of this list and create a dictionary of key-values pairs that looks like</p>

<pre><code>dictionary_list1 = {'EW':'G:B&lt;&lt;LADHFSSFAFFF', 'CB':'E:OWTOWTW', 'PP':'E:A,A&lt;F&lt;AF', 'GR':'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX':'F:-111', 'DS':'f:115.5', 'MW':'AA:0', 'MA':'A:0XT:i:0', 'EW':'EE:KJERWEWERKJWE'}
</code></pre>

<p>How does one parse/split the list above <code>list1</code> to do this? My first instinct was to try <code>try1 = list1.split(":")</code>, but then I think it is impossible to retrieve the "key" for this list, as there are multiple colons <code>:</code></p>

<p>What is the most pythonic way to do this? </p>

<p>You can specify a maximum number of times to split with the second argument to <a href="https://docs.python.org/3.5/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a>.</p>

<pre><code>list1 = ['EW:G:B&lt;&lt;LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A&lt;F&lt;AF', 'GR:A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7', 'SX:F:-111', 'DS:f:115.5', 'MW:AA:0', 'MA:A:0XT:i:0', 'EW:EE:KJERWEWERKJWE']
d = dict(item.split(':', 1) for item in list1)
</code></pre>

<p>Result:</p>

<pre><code>&gt;&gt;&gt; import pprint
&gt;&gt;&gt; pprint.pprint(d)
{'CB': 'E:OWTOWTW',
 'DS': 'f:115.5',
 'EW': 'EE:KJERWEWERKJWE',
 'GR': 'A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7',
 'MA': 'A:0XT:i:0',
 'MW': 'AA:0',
 'PP': 'E:A,A&lt;F&lt;AF',
 'SX': 'F:-111'}
</code></pre>

<p>If you'd like to keep track of values for non-unique keys, like <code>'EW:G:B&lt;&lt;LADHFSSFAFFF'</code> and <code>'EW:EE:KJERWEWERKJWE'</code>, you could add keys to a <code>collections.defaultdict</code>:</p>

<pre><code>import collections
d = collections.defaultdict(list)
for item in list1:
    k,v = item.split(':', 1)
    d[k].append(v)
</code></pre>

<p>Result:</p>

<pre><code>&gt;&gt;&gt; pprint.pprint(d)
{'CB': ['E:OWTOWTW'],
 'DS': ['f:115.5'],
 'EW': ['G:B&lt;&lt;LADHFSSFAFFF', 'EE:KJERWEWERKJWE'],
 'GR': ['A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7'],
 'MA': ['A:0XT:i:0'],
 'MW': ['AA:0'],
 'PP': ['E:A,A&lt;F&lt;AF'],
 'SX': ['F:-111']}
</code></pre>

python dictionary split