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 - 如何将字典列表转换为字符串

python - 在 Python 中,如何响应对象上不存在的方法调用?

python - 减小 basemap 中使用的标记的大小并获得全屏

python - eclipse-python IDE if else 匹配行/指示器

python - 如何获取 pandas 数据框的字符串列表?

c - 在 C 中使用 (void *) 列出

python - 使用列表 Python 映射列数据框

python - 如何用 python "join"两个文本文件?

python - 如何使用 twine 将新版本的项目上传到 PyPI?

python - 如何移动 Pandas Dataframe 列?