jamieb
jamieb

Reputation: 10033

How to slice a string in Python using a dictionary containing character positions?

I have a dictionary containing the character positions of different fields in a string. I'd like to use that information to slice the string. I'm not really sure how to best explain this, but the example should make it clear:

input:

mappings = {'name': (0,4), 'job': (4,11), 'color': (11, 15)}
data = "JohnChemistBlue"

desired output:

{'name': 'John', 'job': 'Chemist', 'color': 'Blue'}

Please disregard the fact that jobs, colors and names obviously vary in character length. I'm parsing fixed-length fields but simplified it here for illustrative purposes.

Upvotes: 2

Views: 202

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799190

>>> dict((f, data[slice(*p)]) for f, p in mappings.iteritems())
{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}

Upvotes: 10

rob mayoff
rob mayoff

Reputation: 385920

dict([(name, data[range[0]:range[1]]) for name, range in mappings.iteritems()])

Upvotes: 4

Vlad
Vlad

Reputation: 18633

>>> dict([(k, data[ mappings[k][0]:mappings[k][1] ]) for k in mappings])
{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}

or with a generator instead of a list (probably more efficient):

>>> dict(((k, data[ mappings[k][0]:mappings[k][1] ]) for k in mappings))
{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}

Upvotes: 3

Related Questions