By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,089 Members | 2,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,089 IT Pros & Developers. It's quick & easy.

Dictionaries again - where do I make a mistake?

P: n/a
Lad
I use the following code to sort dictionary.
Olddict={'r':4,'c':1,'d':2,'e':3,'f':2}
Newdict={}
i = [(val, key) for (key, val) in Olddict.items()]
i.sort() # by val
i.reverse() # Get largest first.
for (val, key) in i:
print key,val
Newdict[key]=val
print Olddict
print Newdict
Sorting seems to be OK,.
the command
print key,val
prints the proper values
but I can not create Newdict to be sorted properly.

Where do I make a mistake?
Thank you for help.
L

Oct 19 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Lad wrote:
Sorting seems to be OK,.
the command
print key,val
prints the proper values
but I can not create Newdict to be sorted properly.

Where do I make a mistake?
Thank you for help.
Dictionaries are unordered -- the order in which items come out is
unspecified. It's based on the details of their internal storage mechanism (a
hash table), and you can't control it at all.

If you need your pairs in a certain order, you'll have to use a list of tuples.

Dustin
Oct 19 '06 #2

P: n/a
but I can not create Newdict to be sorted properly.
>
Where do I make a mistake?
By assuming that dictionaries *can* be sorted.

For more reading:
http://aspn.activestate.com/ASPN/Pyt...k/Recipe/52306
http://aspn.activestate.com/ASPN/Coo.../Recipe/107747

They're intrinsically an unsorted datatype.

-tkc

Oct 19 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.