Marcin Stępnicki wrote:
> Hello.
> 
> I thought I understand this, but apparently I don't :(. I'm missing
> something very basic and fundamental here, so redirecting me to the
> related documentation is welcomed as well as providing working code :).
> 
> Trivial example which works as expected:
> 
>>>> x = {'a':123, 'b': 456}
>>>> y = x 
>>>> x['a']=890
>>>> y
> {'a': 890, 'b': 456}
> 
> Now, let's try something more sophisticated (it's not real world example,
> I've made up the problem which I think illustrates my issue). Let's say
> I've got such a structure:
> 
> results = [ {'a': 12, 'b': 30 },
>             {'a': 13, 'b': 40 } ]
> 
> I'd like to have each row and column in separate object of self-made
> classes.:
> 
> class mycolumn():
>   def __init__(self, resultset, row, col):
>       self.value = resultset[row][col]
>   def __str__(self):
>       return 'Column value: %s' % self.value
> 
> class myrow():
>   def __init__(self):
>       self.container = {}
>   def __str__ (self):
>       return self.container
> 
> results = [
>       {'a': 12, 'b' :30 },
>         {'a': 13, 'b' :40 } 
> ]
> 
> mystruct = []
> 
> for row in results:
>       mystruct.append ( myrow() )
>       for col in row:
>               mystruct [len(mystruct)-1].container[col] = \
>                        mycolumn(results, results.index(row), col)
> 
> print mystruct[0].container['b'] # 12
> results[0]['b'] = 50             # 
> print mystruct[0].container['b'] # also 12 :/
> 
> In other words, I'd like to "map" the results to myrow and mycolumn
> objects, and have these new objects' values changed when I change "results".
> 
> I hope I explained it well enough :). Thank you for your time.
> 

Would this work for you?

class myrow():
  def __init__(self, idict = {}):
        self.container = idict
  def __str__ (self):
        return self.container.__str__()

results = [
        {'a': 12, 'b' :30 },
        {'a': 13, 'b' :40 }
]

mystruct = []

for row in results:
    mystruct.append(myrow(row))

results[1]['b'] = 444

print results  # [{'a': 12, 'b': 30}, {'a': 13, 'b': 444}]

print mystruct # does not work ok , you should probably define
               # mystruct's __str__ method properly

# But, save for the __str__ thingy, the rest is ok.

for row in mystruct:
    print row

# {'a': 12, 'b': 30}
# {'a': 13, 'b': 444}

HTH






-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to