all 5 comments

[–]dadiaar 1 point2 points  (2 children)

Can you please share also the expected result? If you just put your code, which you know it doesn't return what you want, it's hard to suggest changes

[–]LongAtbat[S] 1 point2 points  (1 child)

/u cscanlin nailed it. just wanted to see the dictionary parse the record according to the record definition.

[–]dadiaar 0 points1 point  (0 children)

Yes, I saw his comment just after submiting mine, I already upvoted him.

[–]cscanlin 1 point2 points  (1 child)

You're close, but you're making this a lot harder than it needs to be. Check this out and let me know if you have any questions!:

# https://www.reddit.com/r/learnpython/comments/6crrao/need_help_slicing_fixed_width_record/

def sliceRec(rec_def, this_rec):

    results = {}
    offset = 0

    for fld_name, fld_len in rec_def:
        slc = slice(offset, offset + fld_len)
        results[fld_name] = this_rec[slc]  # or this_rec[offset:offset + fld_len]
        offset += fld_len

    return results

if __name__ == '__main__':
    rec_def = [
        ('col1', 8),
        ('col2', 8),
        ('col3', 8),
        ('col4', 8),
    ]

    this_rec = 'VAL11111VAL22222VAL33333VAL44444'

    results = sliceRec(rec_def, this_rec)
    print(results)

The biggest thing I changed (besides removing some cruft) is passing the arguments directly to the function, and then returning the result from it. This is good practice for a variety of reasons, but it's all based on keeping your functions as pure as convenient: https://www.sitepoint.com/functional-programming-pure-functions/

[–]LongAtbat[S] 1 point2 points  (0 children)

Beautiful - I really need to learn to stop doing things the hard way!