Home > database >  How to split the given 'key-value' list into two lists separated as 'keys' and &
How to split the given 'key-value' list into two lists separated as 'keys' and &

Time:01-03

This is my List

List = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']

I need to separate the List into two differnt List's sepearted as 'keys' and 'values'

List = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']

KeyList

KeyList = ['function', 'string', 'hello', 'new', 'test']

ValueList

ValueList = ['function1', 'string1', 'hello1', 'new1', 'test1']

CodePudding user response:

There are different possible approach. One is the method proposed by Tim, but if you are not familiar with re you could also do:

List = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']

KeyList = []
ValueList = []
for item in List:
    val = item.split(' = ')
    KeyList.append(val[0])
    ValueList.append(val[1])
    
print(KeyList)
print(ValueList)

and the output is:

['function', 'string', 'hello', 'new', 'test']
['function1', 'string1', 'hello1', 'new1', 'test1']

CodePudding user response:

You can simply use split(" = ") and unzip the list of key-value pairs to two tuples:

keys, values = zip(*map(lambda s: s.split(" = "), List))

# keys
# >>> ('function', 'string', 'hello', 'new', 'test')
# values
# >>>('function1', 'string1', 'hello1', 'new1', 'test1')

This is based on the fact that zip(*a_zipped_iterable) works as an unzipping function.

CodePudding user response:

We can use re.findall here:

inp = ['function = function1', 'string = string1', 'hello = hello1', 'new = new1', 'test = test1']
keys = [re.findall(r'(\w ) =', x)[0] for x in inp]
vals = [re.findall(r'\w  = (\w )', x)[0] for x in inp]

CodePudding user response:

keys = [pair[0] for pair in pairs]
values = [pair[1] for pair in pairs]
  • Related