我必须从字符串列表中生成键字典,值对的列表。例如,我有一个这样的列表
my_list = ["John","Google","yes","Sara","TCS","no","John","facebook","yes"]
我希望输出如下:
[
{"name":"John","company":"Google","avaiable":"yes"},
{"name":"Sara","company":"TCS","avaiable":"No"},
{"name":"John","company":"facebook","avaiable":"yes"},
]
答案 0 :(得分:6)
您可以循环浏览列表。您可以按3步将变量放入循环内(下面将为“ i”)。
my_new_list = []
for i in range(0, len(my_list), 3):
my_dict = {}
my_dict['name'] = my_list[i]
my_dict['company'] = my_list[i+1]
my_dict['available'] = my_list[i+2]
my_new_list.append(my_dict)
答案 1 :(得分:2)
下面的代码段应该为您完成。这里的想法是弄清楚列表的长度,并使用列表理解来构建列表字典。假设是:
my_list = ["John", "Google", "yes", "Sara", "TCS", "no", "John", "facebook", "yes"]
list_len = len(my_list)
dictionary_list = [
{"name": my_list[i], "company": my_list[i + 1], "available": my_list[i + 2]}
for i in range(0, list_len, 3)
]
print("dictionary list = %s" % (dictionary_list))
输出:
[{'available': 'yes', 'company': 'Google', 'name': 'John'}, {'available': 'no', 'company': 'TCS', 'name': 'Sara'}, {'available': 'yes', 'company': 'facebook', 'name': 'John'}]
答案 2 :(得分:0)
[
{"name": item[0], "company": item[1], "available": item[2]}
for item in [my_list[i : i + 3] for i in range(0, len(my_list), 3)]
]