如何从python中的类访问字典值?

如何从python中的类访问字典值?,python,class,dictionary,key,Python,Class,Dictionary,Key,我正在尝试使用类创建字典,代码如下: import numpy as np import collections class Graph: def __init__(self): self.graph = collections.defaultdict(dict) def add_edge(self, u, v, weight = 1, directed = True): self.graph[u][v] = weight i

我正在尝试使用类创建字典,代码如下:

import numpy as np
import collections


class Graph:
    def __init__(self):
        self.graph = collections.defaultdict(dict)

    def add_edge(self, u, v, weight = 1, directed = True):
        self.graph[u][v] = weight
        if not directed:
            self.graph[v][u] = weight

    def __str__(self):
        to_return = ''
        for vertex in self.graph:
            to_return += str(vertex) + ': '
            for edge in self.graph[vertex]:
                to_return +=  '(' + str(edge) + ', ' + str(self.graph[vertex][edge]) + ')'
                to_return += '   '

            to_return += '\n'
        return to_return

link_i = [1, 1, 3, 3, 3, 4, 4, 5, 5, 6]
link_j = [2, 3, 1, 2, 5, 5, 6, 6, 4, 4]

if __name__ == '__main__':
    g = Graph()
    for i in range(len(link_i)):
        g.add_edge(link_i[i],link_j[i])

    print(g)
    
for key in g.graph:
    print(g.graph[key])
 
这将提供一个字典输出

{2: 1, 3: 1}
{1: 1, 2: 1, 5: 1}
{5: 1, 6: 1}
{6: 1, 4: 1}
{4: 1}

如何以数组列表而不是字典列表的形式获取输出?

您可以为类提供方法来包装此功能:

class Graph:
    # all the other stuff

    def verteces(self):
        return self.graph.keys()

    def neigbours(self, vertex):
        return list(self.graph[vertex].keys())

g = Graph()
# fill the graph

for v in g.verteces():
    print(g.neighbours(v))

只需访问一个dict属性:
作为g.graph中的键:
请发布包括追溯在内的完整错误。@schwobaseggl是的,可以,但是有没有方法将值返回为int?@Jules将值返回为int,这是什么意思?@Countour Integral抱歉,我不清楚。我已相应地修改了我的问题