unwrap list to payload

Asked by At

I want to unwrap list items in payload. The below is the solution I came up with, but I'm not sure this is the best approach and I'm pretty sure this can be definitely improved:

import ast

texts = ["text1",
         "text2",
         "text3"]

attachments = []

for i, text in enumerate(texts):
    attachment = ''.join(str({
        "text": "some text",
        "action": [
            {
                "text": text,
                "value": str(i+1)
            }
        ]}))
    attachments.append(attachment)

payload = [ast.literal_eval(attachments[i]) for i in range(len(attachments))]

expected result:

[{'text': 'some text', 'action': [{'text': 'text1', 'value': '1'}]}, {'text': 'some text', 'action': [{'text': 'text2', 'value': '2'}]}, {'text': 'some text', 'action': [{'text': 'text3', 'value': '3'}]}]

1 Answers

1
Cloudomation On Best Solutions

You can use list comprehension:

texts = [
    'text1',
    'text2',
    'text3',
]
payload = [
    {
        'text': 'some text',
        'action': [
            {
                'text': text,
                'value': str(i+1),
            }
        ]
    }
    for i, text
    in enumerate(texts)
]
print(payload)

Output

[{'text': 'some text', 'action': [{'text': 'text1', 'value': '1'}]}, {'text': 'some text', 'action': [{'text': 'text2', 'value': '2'}]}, {'text': 'some text', 'action': [{'text': 'text3', 'value': '3'}]}]