Home > Back-end >  how to assign key to each string in the list of strings using python
how to assign key to each string in the list of strings using python

Time:10-19

I have the below list for example consider:

my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']

I need the output list to be like:

output = ['Rule:1,Key:ad,Message:help,Status:green','Rule:2,Key:bc,Message:quote,Status:green','Rule:3,Key:ef,Message:mask,Status:red','Rule:4,Key:ad,Message:help,Status:green']

also how to traverse through the above list and identify the rule, key, message and status and print them alone like below

Rule:1
Key:ad
Message:help
Status:green

Need help on this.

I have tried the below:

for i in my_list:
    for j in i:
        output.append(j)

CodePudding user response:

I need the output list to be like:

solution

The idea is just to split each string and then format the output string accordingly.

output = ["Rule:{},Key:{},Message:{},Status:{}".format(*s.split(',')) for s in my_list]

demo

my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']
output = ["Rule:{},Key:{},Message:{},Status:{}".format(*s.split(',')) for s in my_list]
print(output)

  • output

    ['Rule:1,Key:ad,Message:help,Status:green', 'Rule:2,Key:bc,Message:quote,Status:green', 'Rule:3,Key:ef,Message:mask,Status:red', 'Rule:4,Key:ad,Message:help,Status:green']
    

How to traverse through the above list

for another question

There are different way, here is a simple one

for line in output:
    for entry in line.split(","):
        [key,value] = entry.split(":")    # this is the traverse through

CodePudding user response:

With a list comprehension:

my_list = ['1,ad,help,green','2,bc,quote,green','3,ef,mask,red','4,ad,help,green']
words = ['Rule', 'Key', 'Message', 'Status']

out = [','.join([':'.join(x) for x in zip(words, s.split(','))]) for s in my_list]

Output:

['Rule:1,Key:ad,Message:help,Status:green',
 'Rule:2,Key:bc,Message:quote,Status:green',
 'Rule:3,Key:ef,Message:mask,Status:red',
 'Rule:4,Key:ad,Message:help,Status:green']

print as several lines

for s in my_list:
    for x in zip(words, s.split(',')):
        print(*x, sep=':')

Output:

Rule:1
Key:ad
Message:help
Status:green
Rule:2
Key:bc
Message:quote
Status:green
Rule:3
Key:ef
Message:mask
Status:red
Rule:4
Key:ad
Message:help
Status:green
  • Related