Home > Net >  I want to add a 'texts' list with multiple random values to the dictionary
I want to add a 'texts' list with multiple random values to the dictionary

Time:04-25

I want to loop through the AB test results and add a 'texts' list to the dictionary.

The 'texts' list is always a pair of 4 values, resulting in a list with 8 or 12 values.

100 such lists will be generated.

texts = [
    [
    'A text',
    '89',
    '71%',
    '10%',

    'B text',
    '110',
    '50%',
    '9%',

    'C text',
    '60'
    '30%',
    '4%'
    ],    
    [
    'A text',
    '89',
    '71%',
    '10%',

    'B text',
    '110',
    '50%',
    '9%',
    ]
    ]


dic = {
    'title': '',
    'trial': '',
    'quality': '',
    'ctr': ''
    }


for ix in texts:
   dic.update(title=ix)

My hand stopped at the thought of using the update method.

dic_list = [
    {
    'title': 'A text',
    'trial': '89',
    'quality': '71%',
    'ctr': '10%',
    }
    
    {
    'title': 'B text',
    'trial': '110',
    'quality': '50%',
    'ctr': '9%',
    }
]

How can I create the above dictionary list?

CodePudding user response:

This is your input data

texts1 = [
'A text', # 1st element
'89', # 2nd element
'71%', # 3rd element
'10%', # 4th element

'B text', # 1st element
'110', # 2nd element
'50%', # 3rd element
'9%', # 4th element

'C text', # 1st element
'60', # 2nd element
'30%', # 3rd element
'4%' # 4th element
]

and here is the solution

split_lists = [texts1[x:x 4] for x in range(0, len(texts1), 4)]
list_of_dicts = []
temp_dict = {}
for (title, trial, quality, ctr) in split_lists:
    temp_dict['title'] = title
    temp_dict['trial'] = trial
    temp_dict['quality'] = quality
    temp_dict['ctr'] = ctr
    list_of_dicts.append(temp_dict)
    # print(temp_dict)

The list must be divisible by 4, since you are having four keys in the result dict.

  • Related