我想在字典中添加一个包含多个随机值的"文本"列表



我想循环遍历AB测试结果并将'文本'列表添加到字典中。

'texts'列表总是一对4个值,结果是一个有8或12个值的列表。

将生成100个这样的列表。

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)

一想到要使用更新方法,我的手就停了下来。

dic_list = [
{
'title': 'A text',
'trial': '89',
'quality': '71%',
'ctr': '10%',
}

{
'title': 'B text',
'trial': '110',
'quality': '50%',
'ctr': '9%',
}
]

如何创建上面的字典列表?

这是您的输入数据

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
]

这是解决方案

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)

列表必须能被4整除,因为结果字典中有四个键。

最新更新