我有两个列表,我想用每个列表创建一个dict,其中键值是一个字符串,然后将这两个词组合成一个,下面是我的列表:
list_1 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
list_2 : ['BACKUP_INFO', 'sqlite_sequence', 'BACKUP_INFO_SEARCH', 'BACKUP_INFO_SEARCH_content', 'BACKUP_INFO_SEARCH_segments', 'BACKUP_INFO_SEARCH_segdir', 'BACKUP_INFO_SEARCH_docsize', 'BACKUP_INFO_SEARCH_stat', 'FILE_INFO', 'FILE_INFO_SEARCH', 'FILE_INFO_SEARCH_content', 'FILE_INFO_SEARCH_segments', 'FILE_INFO_SEARCH_segdir', 'FILE_INFO_SEARCH_docsize', 'FILE_INFO_SEARCH_stat']
List_1应添加dict键值为“id”
List_2应添加dict键值为'table'
然后,上述两个词都应合并成一个词典,形成类似的东西:
{
"output":
{
"id": 1,
"table" : BACKUP_INFO
}
{
"id": 2,
"table" :sqlite_sequence
}
}
但是,我使用
获得以下输出 table_list_out = dict(zip(list_1, list_2))
return { 'output' : {'id' : list_1, 'table_name' : list_2}}
:
{
"output": {
"id": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
],
"table_name": {
"1": "BACKUP_INFO",
"2": "sqlite_sequence",
"3": "BACKUP_INFO_SEARCH",
"4": "BACKUP_INFO_SEARCH_content",
"5": "BACKUP_INFO_SEARCH_segments",
"6": "BACKUP_INFO_SEARCH_segdir",
"7": "BACKUP_INFO_SEARCH_docsize",
"8": "BACKUP_INFO_SEARCH_stat",
"9": "FILE_INFO",
"10": "FILE_INFO_SEARCH",
"11": "FILE_INFO_SEARCH_content",
"12": "FILE_INFO_SEARCH_segments",
"13": "FILE_INFO_SEARCH_segdir",
"14": "FILE_INFO_SEARCH_docsize",
"15": "FILE_INFO_SEARCH_stat"
}
}
}
答案 0 :(得分:5)
您可以使用列表理解:
list_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
list_2 = ['BACKUP_INFO', 'sqlite_sequence', 'BACKUP_INFO_SEARCH', 'BACKUP_INFO_SEARCH_content', 'BACKUP_INFO_SEARCH_segments', 'BACKUP_INFO_SEARCH_segdir', 'BACKUP_INFO_SEARCH_docsize', 'BACKUP_INFO_SEARCH_stat', 'FILE_INFO', 'FILE_INFO_SEARCH', 'FILE_INFO_SEARCH_content', 'FILE_INFO_SEARCH_segments', 'FILE_INFO_SEARCH_segdir', 'FILE_INFO_SEARCH_docsize', 'FILE_INFO_SEARCH_stat']
new_dict = {'output':[{'id':a, 'table':b} for a, b in zip(list_1, list_2)]}
输出:
{'output': [{'table': 'BACKUP_INFO', 'id': 1}, {'table': 'sqlite_sequence', 'id': 2}, {'table': 'BACKUP_INFO_SEARCH', 'id': 3}, {'table': 'BACKUP_INFO_SEARCH_content', 'id': 4}, {'table': 'BACKUP_INFO_SEARCH_segments', 'id': 5}, {'table': 'BACKUP_INFO_SEARCH_segdir', 'id': 6}, {'table': 'BACKUP_INFO_SEARCH_docsize', 'id': 7}, {'table': 'BACKUP_INFO_SEARCH_stat', 'id': 8}, {'table': 'FILE_INFO', 'id': 9}, {'table': 'FILE_INFO_SEARCH', 'id': 10}, {'table': 'FILE_INFO_SEARCH_content', 'id': 11}, {'table': 'FILE_INFO_SEARCH_segments', 'id': 12}, {'table': 'FILE_INFO_SEARCH_segdir', 'id': 13}, {'table': 'FILE_INFO_SEARCH_docsize', 'id': 14}, {'table': 'FILE_INFO_SEARCH_stat', 'id': 15}]}
答案 1 :(得分:2)
从外观上看,你想要的输出是不可能的。请注意,有多个值对应于键:"输出"。
可能是这样的,其中对应于'输出'是一个词典列表。
return {'output': [{'id': x, 'table': y} for x, y in zip(list1, list2)]}
答案 2 :(得分:1)
你可以循环使用它,我确定它有一个单行,但这很清楚。
output = {"output":{} }
for i in xrange(0, len(list_1)):
output["output"][list_2[i]] = list_1[i]
print output