Dictionaries again - where do I make a mistake?

Discussion in 'Python' started by Lad, Oct 19, 2006.

  1. Lad

    Lad Guest

    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
    Lad, Oct 19, 2006
    #1
    1. Advertising

  2. 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
    Dustin J. Mitchell, Oct 19, 2006
    #2
    1. Advertising

  3. Lad

    Tim Chase Guest

    Tim Chase, Oct 19, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Johny
    Replies:
    4
    Views:
    287
    Carsten Haese
    Feb 16, 2007
  2. cong
    Replies:
    2
    Views:
    368
  3. lysdexia
    Replies:
    6
    Views:
    476
    John Machin
    Dec 2, 2007
  4. Brandon
    Replies:
    12
    Views:
    472
    Brandon
    Aug 15, 2008
  5. Savas Ates

    question mistake again

    Savas Ates, Jun 12, 2004, in forum: ASP General
    Replies:
    3
    Views:
    90
    Ken Schaefer
    Jun 12, 2004
Loading...

Share This Page