Python: sorting

Hi I am doing a loop so I can get information about the data, but since this is sorting alphabetically, not as I hit the loop ...

Is it possible to somehow disable alphabetical sorting?

here's how to do it

data = {}
for item in container:
  data[item] = {}
  ...
  for key, val in item_container.iteritems():
    ...
    data[item][key] = val

      

give me something like this

data = {
  A : { K1 : V1, K2 : V2, K3 : V3 },
  B : { K1 : V1, K2 : V2, K3 : V3 },
  C : { K1 : V1, K2 : V2, K3 : V3 }
}

      

and I want it to be the way I go through the loop for example.

data = {
  B : {K2 : V2, K3 : V3, K1 : V1},
  A : {K1 : V1, K2 : V2, K3 : V3},
  C : {K3 : V3, K1 : V1, K2 : V2}
}

      

+2


a source to share


3 answers


If you really need to use a dictionary, not a list, take a look at the new OrderedDict (Python 3.1, available soon in Python 2.7). This will preserve the order in which its elements were added.



from collections import OrderedDict
data = OrderedDict()
for item in container:
  data[item] = OrderedDict()
  ...
  for key, val in item_container.iteritems():
    ...
    data[item][key] = val

      

+5


a source


You don't have to rely on the sort order of the data in the dict; since this is just a set of key / value pairs, ordering is not guaranteed by the underlying implementation and may change in a future version.



+3


a source


You can use a list of lists, not a dict dict. Each item will be a tuple (key, value). Of course, this means you won't be able to retrieve items using keys, but it will preserve order. I'm not sure if this is a good idea because I really don't know what you are trying to do, but this is an option.

0


a source







All Articles