2

hi im doing a loop so i could get dict of data, but since its a dict it's sorting alphabetical and not as i push it trought the loop ...

is it possible to somehow turn off alphabetical sorting?

here is how do i do that

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

whitch 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 as i was going throught the loop, e.g.

data = {
  B : {K2 : V2, K3 : V3, K1 : V1},
  A : {K1 : V1, K2 : V2, K3 : V3},
  C : {K3 : V3, K1 : V1, K2 : V2}
}
1
  • 7
    It only seems alphabetical by chance. If you add more strings to it, or other items, you'll see that it's not alphabetical at all. Dicts have no reliable order. Commented Apr 13, 2010 at 14:24

3 Answers 3

5

If you really need to use a dictionary and not a list, take a look at the new OrderedDict (Python 3.1, soon to be available in Python 2.7, too). This will preserve the order in which its items 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
Sign up to request clarification or add additional context in comments.

2 Comments

I suggest you add a link to the package that provides OrderedDict for Python 2.4 through 2.6: pypi.python.org/pypi/ordereddict
Oh, great - I didn't know about that. Well, you have already added the link, not much left for me to do :)
3

You should not be relying on the sort order of data in a dict; since it is just a collection of key/value pairs, the ordering is not guaranteed by the underlying implementation and could change in a future version.

1 Comment

For more information, see: stackoverflow.com/questions/613183/…
0

You can use a list of lists, instead of a dict of dicts. Each element would be a tuple of (key,value). Of course, this means you won't be able to retrieve elements by keys, but it will preserve order. I'm not sure if its a good idea, because I don't really know what you're trying to do, but its an option.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.