How can I only parse / split this list with multiple colons in each element? Create dictionary

I have the following Python list:

list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<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']

I would like to take entries from this list and create a dictionary of key-value pairs that looks like

dictionary_list1 = {'EW':'G:B<<LADHFSSFAFFF', 'CB':'E:OWTOWTW', 'PP':'E:A,A<F<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'}

How to parse / split the list above list1to do this? My first instinct was to try try1 = list1.split(":"), but then I think it’s impossible to get a β€œkey” for this list, since there are a few colons:

What is the most pythonic way to do this?

+4
source share
2 answers

You can specify the maximum number of times to divide the second argument by split.

list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<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)

Result:

>>> import pprint
>>> 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<F<AF',
 'SX': 'F:-111'}

- , 'EW:G:B<<LADHFSSFAFFF' 'EW:EE:KJERWEWERKJWE', collections.defaultdict:

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

:

>>> pprint.pprint(d)
{'CB': ['E:OWTOWTW'],
 'DS': ['f:115.5'],
 'EW': ['G:B<<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<F<AF'],
 'SX': ['F:-111']}
+5

str.partition

list1 = ['EW:G:B<<LADHFSSFAFFF', 'CB:E:OWTOWTW', 'PP:E:A,A<F<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([t for t in x.partition(':') if t!=':'] for x in list1)

# or more simply as TigerhawkT3 mentioned in the comment
d = dict(x.partition(':')[::2] for x in list1)

for k, v in d.items():
    print('{}: {}'.format(k, v))

:

MW: AA:0
CB: E:OWTOWTW
GR: A:OUO-1-XXX-EGD:forthyFive:1:HMJeCXX:7
PP: E:A,A<F<AF
EW: EE:KJERWEWERKJWE
SX: F:-111
DS: f:115.5
MA: A:0XT:i:0
+2

Source: https://habr.com/ru/post/1657018/


All Articles