Alvaro Gomez
Alvaro Gomez

Reputation: 360

Advanced array structure

My dictionary has the following structure:

a = 'stringA'
b = 'stringB'
c = 'stringC'

endpoints = {
    'foo1': a + 'string1' + b,
    'foo2' : a + 'string2' + c + 'string3' + b,
}

My problem is the following: when I call endpoints['foo2'], I get the expected array value. However, when I change the value of, for instance, c between the array declaration and the usage of endpoints['foo2'], the value of c is not updated.

Any idea of why this happens and how can it be solved?

PS: I know this could be done creating a simple function, but I think that would be quite more inefficient.

Upvotes: 2

Views: 76

Answers (1)

Jan
Jan

Reputation: 1504

You could do this:

a = ['stringA']
b = ['stringB']
c = ['stringC']

endpoints = {
    'foo1': a ,
    'foo2' : b
}

print(endpoints['foo1']) #returns "[stringA]"

a[0]='otherString'

print(endpoints['foo1']) #returns "[otherString]"

You can do this, because you can change the values in a list without changing the reference;

a and endpoints are still using the same space for a

This is not possible for pure Strings, because you can not change them without a new assignment. Strings in Python are immutable.

Edit: Another possibility would be to create your own string class.

This removes the [] brackets:

class MyStr:

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

    def __repr__(self):
    #this function is called by dict to get a string for the class
        return self.val

    def setVal(self,val):
        self.val=val

a=MyStr("abcd")
b={1:a}
print(b) #prints {1:"abcd"}
a.setVal("cdef")
print(b) #prints {1:"cdef"}

Disclaimer: As explained in the comments I am still using python 2.7

While Python 3 and 2.7 are mostly compatible, there might be some smaller bugs when trying to use this.

Upvotes: 2

Related Questions