I have a dicationary


Obviously when u print it the dictionary doesnt keep the order you put them in. how do i have a dictionary that has it the way i input them? I looked online, but not sure to you cmp, lambda, etc?

Thanks for the help.

Recommended Answers

All 8 Replies

I know there are modules out there for sorted dictionaries, but out of curiosity why do you want to do this?

well actually I am outputting it as a json.dump of the dictionary. I do not know if there is another way in JSON, I havent found any to have it output in a sorted way for json. The reason why is b/c I have it in a certain protocol for the server I am writing for a fun project of mine. and it reads out a format of the above.

im actually not sure why that happens, nor have i ever had a situation where i needed them to stay in order..

x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> x
{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one': 1}

dicts sort their keys in alphabetical or numerical order... If order is very important to you... you might want to use 2 lists..

>>> x = ['five', 'one', 'four', 'two', 'three']
>>> y = [5, 1, 4, 2, 3]
>>> for i in y:
	print 'key: %s     value: %s' % (i, x[y.index(i)])

key: 5     value: five
key: 1     value: one
key: 4     value: four
key: 2     value: two
key: 3     value: three

Wish i had a better anwser for you... I just have never had an issue where order was important :(

thanks for the suggestion anyways.. i appreciate it

just an afterthought.... You could keep your dict and just keep a list to remember it's order...

>>> x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> y = ['two', 'one', 'five', 'three', 'four']
>>> for i in y:
	print 'key: %s value: %s' % (i, x[i])

key: two value: 2
key: one value: 1
key: five value: 5
key: three value: 3
key: four value: 4

In python 3 you can do

from collections import OrderedDict

which gives you a class which remembers insertion order.
For older pythons, you can try to use a class found on the web like http://code.activestate.com/recipes/107747/.

wow thanks for the help i appreciate it... that is exactly what I am looking for

Just a note: dictionaries keep their keys in a hash order to speed up searches. If you want to keep the entry order you can just use a list of (key, value) tuples which you can also sort if need be.

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.