In [32]: from collections import defaultdict
...: d = defaultdict(list)
...: d['first'].append(1)
...: print(d['second']) # simply accessing a non-existant key
...: # creates the default value - an empty list
...: print(d)
...:
[]
defaultdict(<class 'list'>, {'first': [1], 'second': []})
# Initialize your dictionary
new_dict = dict()
# Add each list "manually"
new_dict[0] = ['your', 'list', 'elements'] #
# Loop through the available lists and add them to your dictionary
for i in range(100):
new_dict[i] = list_of_lists[i]
“如何动态设置Python字典的长度(即如何动态设置字典中键值的数目)”
字典的每个值(将是一个整数)都应该指向一个列表
首先,上面第一句中的键值在Python中被称为键。第二,这些键“指向”的东西被称为值。因此,您的列表是值。你知道吗
回答你的第一个问题:你不能设置字典的长度。相反,您只需向字典添加键值对(或删除键),这就是动态控制字典长度的方式。你知道吗
在我看来,你真正想要的是一个
defaultdict
:对于第一部分,可以使用
None
初始化字典。见here。你知道吗对于第二部分,字典已经由键值对组成,因此如果希望字典的整数索引引用列表,可以执行以下操作:
相关问题 更多 >
编程相关推荐