在字典中附加一个 int 键
Appending an int key in a dictionary
我正在尝试根据以下列表创建字典:
link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]
link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]
nodes = [1, 2, 3, 4, 5, 6]
# Creating a dictionary containing nodes and their incoming links:
out_dict = {}
for i in nodes:
for j in range(0,len(link_i)):
if (link_i[j] == i):
if i not in out_dict:
out_dict[i] = link_j[j]
elif i in out_dict:
out_dict[i].append(link_j[j])
但是,我无法附加密钥,因为它的类型是 int。我收到错误:
line 21, in <module>
out_dict[i].append(link_j[j])
AttributeError: 'int' object has no attribute 'append'
我试图让输出为:
{1: [2, 3], 3: [1, 2, 5], 4: [5, 6], 5: [6, 4], 6: [4]}
您需要更改:
if i not in out_dict:
out_dict[i] = link_j[j]
至
if i not in out_dict:
out_dict[i] = [link_j[j]]
这是因为在您第一次将键“i”添加到 out_dict 之后,您将为其分配一个 int 类型的值。为了能够添加到此,稍后,它需要是可变数据类型,例如具有属性追加的列表。这并不能解决您所有的问题,因为即使进行了此更改,您仍然无法获得所需的输出,但它可以让您进一步调试。
为了保持代码简单,您可以使用字典 comprehension 并将每个节点的默认值设置为空列表。这样你就不需要检查节点是否已经是字典的一部分,你可以只附加链接。
link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]
nodes = [1, 2, 3, 4, 5, 6]
# Creating a dictionary containing nodes and their incoming links:
# fill the dict with empty lists for each node
out_dict = {node: [] for node in nodes}
for i in nodes:
for j in range(0,len(link_i)):
if (link_i[j] == i):
# append link to the list for the node
out_dict[i].append(link_j[j])
输出如下所示:
{1: [2, 3], 2: [], 3: [1, 2, 5], 4: [5, 6], 5: [6, 4], 6: [4]}
我正在尝试根据以下列表创建字典:
link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]
link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]
nodes = [1, 2, 3, 4, 5, 6]
# Creating a dictionary containing nodes and their incoming links:
out_dict = {}
for i in nodes:
for j in range(0,len(link_i)):
if (link_i[j] == i):
if i not in out_dict:
out_dict[i] = link_j[j]
elif i in out_dict:
out_dict[i].append(link_j[j])
但是,我无法附加密钥,因为它的类型是 int。我收到错误:
line 21, in <module>
out_dict[i].append(link_j[j])
AttributeError: 'int' object has no attribute 'append'
我试图让输出为:
{1: [2, 3], 3: [1, 2, 5], 4: [5, 6], 5: [6, 4], 6: [4]}
您需要更改:
if i not in out_dict:
out_dict[i] = link_j[j]
至
if i not in out_dict:
out_dict[i] = [link_j[j]]
这是因为在您第一次将键“i”添加到 out_dict 之后,您将为其分配一个 int 类型的值。为了能够添加到此,稍后,它需要是可变数据类型,例如具有属性追加的列表。这并不能解决您所有的问题,因为即使进行了此更改,您仍然无法获得所需的输出,但它可以让您进一步调试。
为了保持代码简单,您可以使用字典 comprehension 并将每个节点的默认值设置为空列表。这样你就不需要检查节点是否已经是字典的一部分,你可以只附加链接。
link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]
nodes = [1, 2, 3, 4, 5, 6]
# Creating a dictionary containing nodes and their incoming links:
# fill the dict with empty lists for each node
out_dict = {node: [] for node in nodes}
for i in nodes:
for j in range(0,len(link_i)):
if (link_i[j] == i):
# append link to the list for the node
out_dict[i].append(link_j[j])
输出如下所示:
{1: [2, 3], 2: [], 3: [1, 2, 5], 4: [5, 6], 5: [6, 4], 6: [4]}