Kwiaci
Kwiaci

Reputation: 41

Getting values from a dictionary

Below is a code which I am working with. My program creates combination of possible positions and gets the last position. Then I want to get the value for that position based on the letter from list A and a dictionary dictionary VALUES. When I execute this code I get:

AttributeError: 'Combination' object has no attribute 'get_value'

X = ['A','B','C']  
Y = ['1','2','3']
VALUES_FOR_X = {'A':1, 'B': 2, 'C':3}

class Combination:   # Creates a list of possible position combinations
    def __init__(self,x,y):
        if (x in X) and (y in Y):
            self.x = x
            self.y = y
        else:
            print "WRONG!!"

    def __repr__ (self):
        return self.x+self.y

class Position:     # Makes operation on the chosen position
    def __init__(self):
        self.xy = []
        for i in X:
            for j in Y:
                self.xy.append(Combination(i,j))

    def choose_last(self):
        return self.xy.pop()

    def get_value(self):
        return self.VALUES_FOR_X()

    def __str__(self):
        return "List contains: " + str(self.xy)

pos = Position()
print pos
last_item = pos.choose_last()
print "Last item is:", last_item
print  last_item.get_value()

Does anyone knows how to change this code in the simplest way to make it working?

The logic of this program: We have possible X,Y positions. We create all possible combinations. Then we chose the last position from possible combinations, eg.: C3 Untill here program works perfectly Now I want to get values of position C3. Using dictionary value for 'C' in C3 is 3. And I want to print this value (3).

To do this I added method:

def get_value(self):
    return self.VALUES_FOR_X()

Upvotes: 0

Views: 197

Answers (1)

Mailerdaimon
Mailerdaimon

Reputation: 6080

If I understand you Problem correctly this is the Solution:

X = ['A','B','C']
Y = ['1','2','3']
VALUES_FOR_X = {'A':1, 'B': 2, 'C':3}

class Combination:   # Creates a list of possible position combinations
    def __init__(self,x,y):
        if (x in X) and (y in Y):
            self.x = x
            self.y = y
        else:
            print "WRONG!!"

    def get_value(self):
        return VALUES_FOR_X[self.x]

    def __repr__ (self):
        return self.x+self.y

class Position:     # Makes operation on the chosen position
    def __init__(self):
        self.xy = []
        for i in X:
            for j in Y:
                self.xy.append(Combination(i,j))

    def choose_last(self):
        return self.xy.pop()



    def __str__(self):
        return "List contains: " + str(self.xy)

pos = Position()
print pos
last_item = pos.choose_last()
print "Last item is:", last_item
print  last_item.get_value()

My output is:

>>>  List contains: [A1, A2, A3, B1, B2, B3, C1, C2, C3]  
>>>  Last item is: C3  
>>>  3

Upvotes: 1

Related Questions