dtalbot
dtalbot

Reputation: 13

Python: reordering a string(list) based on a previous list order

I am stumped, any help would be great, this is way above my pay grade:

I have string of key values which when identified are provided a number. To make matters more complicated is that they are identified as either an int or string.

The objective is that when a new string is processed, it should use the original key order that might have been previously defined. Additionally the value could always be different

Here is an example of the information gained from the first string:

import re
int_dict = {}
string_dict = {}
int_number = 1
string_number = 1
firstlist = "key_a=apples key_z=4 key_e=pears key_b=bananas key_r=3"
re_result = re.findall(r'(\w+)=(\w+)', firstlist)
for i in re_result:
   if i[1].isdigit():
        int_dict[int_number] = i[0]
        int_number += 1
   else:
        string_dict[string_number] = i[0]
        string_number += 1

print int_dict
>>> {1: 'key_z', 2: 'key_r'}
print string_dict
>>> {1: 'key_a', 2: 'key_e', 3: 'key_b'}

The second line could be as follows:

secondstring = "key_r=54 key_a=grapes key_b=nuts key_z=7 key_r=22"

I would like the string re-ordered based on the previous string, in the second string there is also a new key which should just take the next increment based on if its a int or string:

secondstring_reordered = "key_a=grapes key_z=7 key_b=nuts key_r=22 key_z=7"

Upvotes: 1

Views: 95

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

Using the first string create a dictionary first, where the key is the key from the string and value is the index of that item in the list returned by firstlist.split()

>>> d = {item.split('=', 1)[0]:i for i, item in enumerate(firstlist.split())}
>>> d
{'key_e': 2, 'key_b': 3, 'key_a': 0, 'key_r': 4, 'key_z': 1}

Now using this dictionary you can sort the list returned by secondstring.split(), and then join it back using str.join:

>>> ' '.join(sorted((item for item in secondstring.split()),
                                                 key=lambda x:d[x.split('=',1)[0]]))
'key_a=grapes key_z=7 key_b=nuts key_r=54 key_r=22'

If you're sure that the values in the string will never contain a = then you can change item.split('=', 1) and x.split('=',1)[0] to item.split('=')[1] and x.split('=')[1] respectively.

Upvotes: 1

Related Questions