Dictionary keys not present though they are being added











up vote
0
down vote

favorite












This is my code :



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))


I am not able to find the error in this code.
When the add function is called, I get the True message indicating it is added. The first print statement prints that the number of keys are 4 but after adding the links, it says the keys are 7.
I want to have just 4 even after adding the link.



Thanks for the help !










share|improve this question
























  • hint: try printing some_graph.some_dict
    – mad_
    Nov 8 at 21:41






  • 1




    You are storing instances of class member in some_dict, but you are then trying to look up strings (names) in that dict. member("bob") is not the same as "bob", and furthermore member("bob") != member("bob"); they will be different instances with the same name.
    – Jim Stewart
    Nov 8 at 21:41












  • @mad_ I tried testing that. It does give me the correct result. {pqr: , xyz: , abc: , mno: }. But, my error still remains.
    – ms1941
    Nov 8 at 21:43

















up vote
0
down vote

favorite












This is my code :



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))


I am not able to find the error in this code.
When the add function is called, I get the True message indicating it is added. The first print statement prints that the number of keys are 4 but after adding the links, it says the keys are 7.
I want to have just 4 even after adding the link.



Thanks for the help !










share|improve this question
























  • hint: try printing some_graph.some_dict
    – mad_
    Nov 8 at 21:41






  • 1




    You are storing instances of class member in some_dict, but you are then trying to look up strings (names) in that dict. member("bob") is not the same as "bob", and furthermore member("bob") != member("bob"); they will be different instances with the same name.
    – Jim Stewart
    Nov 8 at 21:41












  • @mad_ I tried testing that. It does give me the correct result. {pqr: , xyz: , abc: , mno: }. But, my error still remains.
    – ms1941
    Nov 8 at 21:43















up vote
0
down vote

favorite









up vote
0
down vote

favorite











This is my code :



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))


I am not able to find the error in this code.
When the add function is called, I get the True message indicating it is added. The first print statement prints that the number of keys are 4 but after adding the links, it says the keys are 7.
I want to have just 4 even after adding the link.



Thanks for the help !










share|improve this question















This is my code :



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))


I am not able to find the error in this code.
When the add function is called, I get the True message indicating it is added. The first print statement prints that the number of keys are 4 but after adding the links, it says the keys are 7.
I want to have just 4 even after adding the link.



Thanks for the help !







python dictionary graph key-value






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 22:17

























asked Nov 8 at 21:37









ms1941

133




133












  • hint: try printing some_graph.some_dict
    – mad_
    Nov 8 at 21:41






  • 1




    You are storing instances of class member in some_dict, but you are then trying to look up strings (names) in that dict. member("bob") is not the same as "bob", and furthermore member("bob") != member("bob"); they will be different instances with the same name.
    – Jim Stewart
    Nov 8 at 21:41












  • @mad_ I tried testing that. It does give me the correct result. {pqr: , xyz: , abc: , mno: }. But, my error still remains.
    – ms1941
    Nov 8 at 21:43




















  • hint: try printing some_graph.some_dict
    – mad_
    Nov 8 at 21:41






  • 1




    You are storing instances of class member in some_dict, but you are then trying to look up strings (names) in that dict. member("bob") is not the same as "bob", and furthermore member("bob") != member("bob"); they will be different instances with the same name.
    – Jim Stewart
    Nov 8 at 21:41












  • @mad_ I tried testing that. It does give me the correct result. {pqr: , xyz: , abc: , mno: }. But, my error still remains.
    – ms1941
    Nov 8 at 21:43


















hint: try printing some_graph.some_dict
– mad_
Nov 8 at 21:41




hint: try printing some_graph.some_dict
– mad_
Nov 8 at 21:41




1




1




You are storing instances of class member in some_dict, but you are then trying to look up strings (names) in that dict. member("bob") is not the same as "bob", and furthermore member("bob") != member("bob"); they will be different instances with the same name.
– Jim Stewart
Nov 8 at 21:41






You are storing instances of class member in some_dict, but you are then trying to look up strings (names) in that dict. member("bob") is not the same as "bob", and furthermore member("bob") != member("bob"); they will be different instances with the same name.
– Jim Stewart
Nov 8 at 21:41














@mad_ I tried testing that. It does give me the correct result. {pqr: , xyz: , abc: , mno: }. But, my error still remains.
– ms1941
Nov 8 at 21:43






@mad_ I tried testing that. It does give me the correct result. {pqr: , xyz: , abc: , mno: }. But, my error still remains.
– ms1941
Nov 8 at 21:43














3 Answers
3






active

oldest

votes

















up vote
1
down vote













Print out the dictionary in question.



print(some_graph.some_dict)


produces



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


The keys of this dictionary are instances of the class member, not the strings in the list list_person.



I you did:



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()


You would get:



abc
True

xyz
True

mno
True

pqr
True





share|improve this answer




























    up vote
    0
    down vote













    You can fix the problem by adding a __contains__() method to your CreateGraph class that expects a string argument called name. How to do this and then use it shown in the code below.



    Note: I have changed all your class names to the CapitalizedWords-style to conform to the PEP8 coding guidelines (in its Naming Conventions section).



    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")


    Here's the output:



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





    share|improve this answer






























      up vote
      -1
      down vote













      You are storing instances as key. call name()to get the name
      try testing like below



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





      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














         

        draft saved


        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53216515%2fdictionary-keys-not-present-though-they-are-being-added%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        1
        down vote













        Print out the dictionary in question.



        print(some_graph.some_dict)


        produces



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


        The keys of this dictionary are instances of the class member, not the strings in the list list_person.



        I you did:



        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()


        You would get:



        abc
        True

        xyz
        True

        mno
        True

        pqr
        True





        share|improve this answer

























          up vote
          1
          down vote













          Print out the dictionary in question.



          print(some_graph.some_dict)


          produces



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


          The keys of this dictionary are instances of the class member, not the strings in the list list_person.



          I you did:



          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()


          You would get:



          abc
          True

          xyz
          True

          mno
          True

          pqr
          True





          share|improve this answer























            up vote
            1
            down vote










            up vote
            1
            down vote









            Print out the dictionary in question.



            print(some_graph.some_dict)


            produces



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


            The keys of this dictionary are instances of the class member, not the strings in the list list_person.



            I you did:



            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()


            You would get:



            abc
            True

            xyz
            True

            mno
            True

            pqr
            True





            share|improve this answer












            Print out the dictionary in question.



            print(some_graph.some_dict)


            produces



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


            The keys of this dictionary are instances of the class member, not the strings in the list list_person.



            I you did:



            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()


            You would get:



            abc
            True

            xyz
            True

            mno
            True

            pqr
            True






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 8 at 21:41









            timgeb

            44.5k106285




            44.5k106285
























                up vote
                0
                down vote













                You can fix the problem by adding a __contains__() method to your CreateGraph class that expects a string argument called name. How to do this and then use it shown in the code below.



                Note: I have changed all your class names to the CapitalizedWords-style to conform to the PEP8 coding guidelines (in its Naming Conventions section).



                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")


                Here's the output:



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





                share|improve this answer



























                  up vote
                  0
                  down vote













                  You can fix the problem by adding a __contains__() method to your CreateGraph class that expects a string argument called name. How to do this and then use it shown in the code below.



                  Note: I have changed all your class names to the CapitalizedWords-style to conform to the PEP8 coding guidelines (in its Naming Conventions section).



                  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")


                  Here's the output:



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





                  share|improve this answer

























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    You can fix the problem by adding a __contains__() method to your CreateGraph class that expects a string argument called name. How to do this and then use it shown in the code below.



                    Note: I have changed all your class names to the CapitalizedWords-style to conform to the PEP8 coding guidelines (in its Naming Conventions section).



                    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")


                    Here's the output:



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





                    share|improve this answer














                    You can fix the problem by adding a __contains__() method to your CreateGraph class that expects a string argument called name. How to do this and then use it shown in the code below.



                    Note: I have changed all your class names to the CapitalizedWords-style to conform to the PEP8 coding guidelines (in its Naming Conventions section).



                    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")


                    Here's the output:



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






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Nov 8 at 22:28

























                    answered Nov 8 at 22:14









                    martineau

                    64.5k887171




                    64.5k887171






















                        up vote
                        -1
                        down vote













                        You are storing instances as key. call name()to get the name
                        try testing like below



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





                        share|improve this answer

























                          up vote
                          -1
                          down vote













                          You are storing instances as key. call name()to get the name
                          try testing like below



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





                          share|improve this answer























                            up vote
                            -1
                            down vote










                            up vote
                            -1
                            down vote









                            You are storing instances as key. call name()to get the name
                            try testing like below



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





                            share|improve this answer












                            You are storing instances as key. call name()to get the name
                            try testing like below



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






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 8 at 21:44









                            mad_

                            3,1121920




                            3,1121920






























                                 

                                draft saved


                                draft discarded



















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53216515%2fdictionary-keys-not-present-though-they-are-being-added%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Guess what letter conforming each word

                                Port of Spain

                                Run scheduled task as local user group (not BUILTIN)