首页 > 解决方案 > 如何在字典Python中添加列表作为值

问题描述

我正在尝试创建一个字典,其中键是字符串,值是列表。类似的东西

l1 = ['a', 'b', 'c']

我想在 for 循环的每次迭代中添加类似于该列表的列表。

我试过这个

dicc['first'].append(l1)

出口应该是这样的:

dicc={'first': ['a', 'b', 'c']}

我总是遇到同样的错误:list indices must be integers or slices, not str

我该怎么做?

标签: pythondictionary

解决方案


在这种情况下,您必须将对象分配给字典中的键的列表,在您的情况下:

dicc['first'] = l1


推荐阅读