jellyberg
jellyberg

Reputation: 188

Changing the value of a variable stored in a dictionary

Sorry if this is a dumb question, I'm struggling to think of another simple way around it.

My code (the relevant bits):

import file2

sliderData = [{'name': 'Number of mountains', 'variable': file2.NUMMOUNTAINS},
              {'name': 'Number of trees', 'variable': file2.NUMTREES}

for i in range(len(self.sliders)):  # self.sliders is a list of Slider() objects
    self.sliderData[i]['variable'] = self.sliders[i].update()  # update() returns an int

print int(file2.NUMMOUNTAINS)

I can't work out how to make it update the variable stored in sliderData[i]['variable'] (i.e. changing file2.NUMMOUNTAINS itself). It seems to just change the value stored in the dictionary.

Any ideas?

Upvotes: 0

Views: 192

Answers (3)

JML
JML

Reputation: 721

You should add to file2 some kind of method to to make the update, because what you're doing in that code is changing the value (of key 'variable') in the dictionary.

For example you can have in file2 a method that receives a key name and a value, and then change the real value you want to change

class File2:

def __init__(self):
    self.NUMMOUNTAINS = 0
    self.NUMTREES = 0
    pass

def setValue(self, key, value):
    if key == 'Number of mountains':
         self.NUMMOUNTAINS = value
    elif key == 'Number of trees':
         self.NUMMTREES = value

Then in your actual code:

for i in range(len(self.sliders)):  # self.sliders is a list of Slider() objects
    file2.setValue(self.sliderData[i]['name'], self.sliders[i].update())  # update() returns an int

Anyways, this is a poor structure, and if you need to scale it (like having much more elements in the dictionary) it'll be hard and error prone.

Upvotes: 1

furas
furas

Reputation: 142641

It seems file2.NUMMOUNTAINS is int so in dictionary you get copy of value from file2.NUMMOUNTAINS - not reference to variable file2.NUMMOUNTAINS

self.sliderData[i]['variable'] and file2.NUMMOUNTAINS are indenpendent variables.

When you change self.sliderData[i]['variable'] it doesn't change file2.NUMMOUNTAINS.
When you change file2.NUMMOUNTAINS it doesn't change self.sliderData[i]['variable'].

Upvotes: -1

jonrsharpe
jonrsharpe

Reputation: 121975

Assuming that file2.NUMMOUNTAINS is an int or float, note that both types are immutable, i.e. cannot be changed in place.

Therefore when you assign the value returned by self.sliders[i].update() to self.sliderData[i]['variable'], this doesn't change file2.NUMMOUNTAIN but instead assigns the dictionary reference to a different object.

A minimal example to display this:

>>> d = {'a': 1}
>>> id(d['a'])
1751629384
>>> d['a'] += 1
>>> d
{'a': 2}
>>> id(d['a'])
1751629400 # different 'id' means different object

You will have to explicitly alter the value of the attribute, e.g.

file2.NUMMOUNTAIN = self.sliderData[0]['variable']

Upvotes: 1

Related Questions