Dictionaries again - where do I make a mistake?

L

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
 
D

Dustin J. Mitchell

Lad said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top