我有两个列表,我想通过索引将它们关联为字典中的键值对。键列表有多个相同的元素。我希望将值列表中的所有元素配对为列表列表。我正在使用 list.append() 方法,但这没有给我所需的输出。关于代码的任何建议,或者我应该以不同的方式看待问题吗?
list1 = ['a', 'b', 'b', 'b', 'c']
list2 = [['1', '2', '3'], ['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12'], ['13', '14', '15']]
combo = {}
for i in range(len(list1)):
if list1[i] in combo:
combo[list1[i]].append(list2[i])
else:
combo[list1[i]] = list2[i]
当前输出:
{'a': ['1', '2', '3'], 'b': ['4', '5', '6', [ '7', '8', '9'], ['10', '11', '12']], 'c': ['13', '14', 15']}
期望的输出:
{'a': [['1', '2', '3']], 'b': [['4', '5', '6'], [ '7', '8', '9'], ['10', '11', '12']], 'c': [['13', '14', 15']]}
最佳答案
使用defaultdict
,空列表作为起始值
result = defaultdict(list)
for key, value in zip(list1, list2):
result[key].append(value)
关于Python:创建列表列表作为字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118472/