Steven Briggs
Steven Briggs

Reputation: 43

How to print class attributes of dictionary key

I am trying to access the content for every node in a dictionary I am making but am not sure how to proceed. For example given the two nodes in the dictionary I would hope to print out the letter M and H.

class Node:
      def __init__(self, content):
        self.content = content

def createLattice():
    Node1 = Node("M")
    Node2 = Node("H")

    lattice = {Node1: [Node2],
         Node2: [Node1]}

    for key in lattice:
         print(key.content())

Upvotes: 0

Views: 62

Answers (3)

HelloWorld
HelloWorld

Reputation: 307

class Node:
    def __init__(self, content):
        self.content = content


def createLattice():
    Node1 = Node("M")
    Node2 = Node("H")

    lattice = {Node1: [Node2],
               Node2: [Node1]}

    for key,value in lattice.items():
        print(key.content)
        print(value[0].content)


createLattice()

Hope this helps. Note that content shouldn't be called with () as it's an attribute not a method. To access the key, value or both in dict, you will need to get them through key(), value() or items().

Upvotes: 1

hunzter
hunzter

Reputation: 598

By creating your init function this way

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

And create your object like this

Node1 = Node("M")
Node2 = Node("H")

You are assigning content as a str, e.g "H".

So when you access it, it is a string, not a function. You cannot use it as key.content(). But use:

key.content

Upvotes: 1

RealPawPaw
RealPawPaw

Reputation: 986

class Node:
      def __init__(self, content):
        self.content = content

def createLattice():
    Node1 = Node("M")
    Node2 = Node("H")

    lattice = {Node1: [Node2],
         Node2: [Node1]}

    for key in lattice:
         print(key.content)

createLattice()

You were accessing an attribute of a class as it were a method! Node.content isn't a method, it's an attribute, so you refer to it as Node.content, not Node.content().

Upvotes: 1

Related Questions