Python:创建列表列表作为字典值

标签 python python-3.x list dictionary

我有两个列表,我想通过索引将它们关联为字典中的键值对。键列表有多个相同的元素。我希望将值列表中的所有元素配对为列表列表。我正在使用 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/

相关文章:

python - 插入很多产品opencart脚本

python - 当数据库中有Python行时,PyMySql游标获取全部返回空

python - 在Python multiprocessing.Process 中,我们必须使用 `__name__ == __main__` 吗?

python - 将列表写入 Excel

python - 值错误: I/O operation on closed file when using **generator** over **list**

python - 如何计算列表中的数字

python - 如何使用用户名前缀映射 url?

python - pipfile 可编辑包位置

python - 将信息从字符串转换为字典

Python while true循环未达到 "except ValueError"