Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Dictionaries again - where do I make a mistake?

Reply
Thread Tools

Dictionaries again - where do I make a mistake?

 
 
Lad
Guest
Posts: n/a
 
      10-19-2006
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

 
Reply With Quote
 
 
 
 
Dustin J. Mitchell
Guest
Posts: n/a
 
      10-19-2006
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
 
Reply With Quote
 
 
 
 
Tim Chase
Guest
Posts: n/a
 
      10-19-2006
> 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



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
updating dictionaries from/to dictionaries Brandon Python 12 08-15-2008 12:35 AM
Pickling dictionaries containing dictionaries: failing,recursion-style! lysdexia Python 6 12-02-2007 12:03 AM
HttpSession gets generated again and again!! PLEASE HELP ME!!!! che Java 2 10-10-2005 10:20 PM
jserve booting again and again amit Java 0 10-02-2003 04:26 PM
How to make tree of dictionaries? Vlad Sirenko Python 2 08-13-2003 07:52 AM



Advertisments