尽管正在添加字典键,但它们不存在

时间:2018-11-08 21:37:36

标签: python dictionary graph key-value

这是我的代码:

class member:

    def __init__(self, name):
        self.name = name

    def get_name(self, name):
        self.name = name

    def __str__(self):
        return self.name

class create_graph:

    def __init__(self):
        self.some_dict = dict()

    def add(self, name):
        if name is None:
            raise TypeError
        print(name not in self.some_dict)
        if name not in self.some_dict:
            self.some_dict[name] = []
        else:
            print(str(name) + "is already present")

    def link(self, p1, p2):
        if p1 in self.some_dict:
            self.some_dict[p1].append(p2)
        else:
            self.some_dict[p1] = [p2]

some_graph = create_graph()

list_person = ['abc', 'xyz', 'mno', 'pqr']

for person in list_person:
    some_graph.add(member(person))

print(len(some_graph.some_dict))

for i in range(len(list_person)-1):
    some_graph.link(i,i+1)

print(len(some_graph.some_dict))

我无法在此代码中找到错误。 调用add函数时,我收到True消息,指示已添加该函数。第一个打印语句打印出键的数量是4,但是在添加链接之后,它说键是7。 即使添加链接后,我也希望只有4个。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

打印出有问题的字典。

print(some_graph.some_dict)

产生

{<__main__.member object at 0x7fe8326abe80>: [], <__main__.member object at 0x7fe8326abeb8>: [], <__main__.member object at 0x7fe8326abe48>: [], <__main__.member object at 0x7fe8326abef0>: []}

此词典的键是类member的实例,而不是列表list_person中的字符串。

我做到了:

persons_in_graph_dict = {k.name for k in some_graph.some_dict}
for person in list_person:
    print(person)
    print(person in persons_in_graph_dict)
    print()

您会得到:

abc
True

xyz
True

mno
True

pqr
True

答案 1 :(得分:0)

您可以通过在您的CreateGraph类中添加一个__contains__()方法来解决该问题,该方法需要一个名为name string 参数。如何执行此操作,然后使用它,如下面的代码所示。

注意:我已将您所有的类名都更改为CapitalizedWords样式,以符合PEP8编码准则(在其Naming Conventions部分中)。

class Member:
    def __init__(self, name):
        self.name = name

    def get_name(self, name):
        self.name = name

    def __str__(self):
        return self.name


class CreateGraph:
    def __init__(self):
        self.some_dict = dict()

    def add(self, name):
        if name is None:
            raise TypeError

        if name not in self.some_dict:
            self.some_dict[name] = Member(name)
        else:
            print("{} is already present".format(name))

    def __contains__(self, name):  # <-- METHOD ADDED.
        return name in self.some_dict


some_graph = CreateGraph()

list_person = ['abc', 'xyz', 'mno', 'pqr']

for person in list_person:
    some_graph.add(person)

print("checking these names in list_person:", list_person)
for person in list_person:
    if person in some_graph:
        print("Present")
    else:
        print("Not present")

以下是输出:

checking these names in list_person: ['abc', 'xyz', 'mno', 'pqr']
Present
Present
Present
Present

答案 2 :(得分:-1)

您将实例存储为键。致电name()以获取名称 尝试进行如下测试

for i in some_graph.some_dict:
    print ((i.name) in list_person)