i have a problem with my python class. it contains a method that goes through all the keys of a multi_dimensional dictionary. The dictionary keys may be in the following order (1->(2,3),2->(5,6)). the problem is when the method attempts to get the keys, sometimes it gets them in the right order (1,2) and sometimes it gets them in the wrong order (2,1). any help will be appreciated. below is a very simple example of what the code might look like

\

class tree:
  tree_as_string = ""
    def __init__(self):
      self.id = ""
      self.daughters = {1 = 'node0', 2 = 'node1'}
    def get_as_string(self):
      s = ''
      for key in self.daughters:
         tree_as_string = s.join([tree_as_string, key])
      return tree_as_string

Dictionary keys are stored in "hash" order, not the order they were entered (a dictionary is an indexed container, not a sequential one). You should either sort the keys, and then use the sorted list to lookup in the dictionary, or use "ordered dictionary", which usually requires importing "collections" depending on your version of Python.

Also, the join() should be outside of the loop. There is no reason to do it every time.

## a dictionary is created with a colon, :, not an equal sign, =
    self.daughters = {1:'node0', 2:'node1'}

def get_as_string(self):
    s = ''
    ## get the keys and convert each key to a string, 
    ## since you want to return one string
    return_list = self.daughters.keys()
    return_list.sort()           ## the keys are now sorted (sort as ints not as strings)
    return_list = [str(x) for x in return_list]     ## convert to a string
    tree_as_string = s.join(return_list)
    return tree_as_string
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.