0
data = ['ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:[email protected] ST:VIC',
        'ID:b22 EM:[email protected] ST:VIC GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215',
        'ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:[email protected]']

I want the following data to be arranged in the order of

key_order = 'ID', 'GE', 'FN', 'LN', 'MN', 'EM', 'ST'

I can do it when there is one string using this code:

data = ['ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:[email protected]']
data = data[0].split()
keyorder = ['ID', 'GE','FN','LN','MN','EM', 'ST']
print(sorted(data, key=lambda x: key_order.index(x.split(':')[0]))) 

['ID:153', 'GE:m', 'FN:John', 'LN:Liu', 'MN:040181010', 'EM:[email protected]', 'ST:NSW']

Also having trouble for the final result to be displayed as:

ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:[email protected] ST:VIC
ID:b22 EM:[email protected] ST:VIC GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215
ID:153 GE:m FN:John LN:Liu MN:040181010 ST:NSW EM:[email protected]

Thanks heaps

3
  • 1
    The second line of your desired output looks incorrect. Commented Jan 20, 2018 at 5:14
  • @James The third, too. Commented Jan 20, 2018 at 5:18
  • yes sorry i realised that and didnt know how to edit and by that time you posted the answer already haha. too quick Commented Jan 20, 2018 at 5:26

1 Answer 1

3

You are very close to the right answer:

def sort_by_key(x):
    return key_order.index(x.split(':')[0])
for d in data:
    print(" ".join(sorted(d.split(), key=sort_by_key)))
#ID:123 GE:m FN:Amir LN:Maleki MN:0400101010 EM:[email protected] ST:VIC
#ID:b22 GE:F FN:Miniyi LN:Li MN:0430101210 MN:0432101215 EM:[email protected] ST:VIC
#ID:153 GE:m FN:John LN:Liu MN:040181010 EM:[email protected] ST:NSW
Sign up to request clarification or add additional context in comments.

1 Comment

omg i struggled with this for weeks and you did it in a few seconds! amazing!! Thank you so much for your help. I really appreciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.