Dictionary Sorting?

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Oct 2006
Posts: 2,564
Reputation: mattyd is an unknown quantity at this point 
Solved Threads: 1
Featured Poster
mattyd's Avatar
mattyd mattyd is offline Offline
Posting Maven

Dictionary Sorting?

 
0
  #1
Dec 2nd, 2006
I am interested in learning if it is indeed possible to sort a Python dict. What I have researched tonight points to that it is not possible, although snippets were posted inferring that you can sort a dict; I tried some of this code and it did not seem to work well if at all.

Any, advice, suggestions, or direction would be greatly appreciated.

Thank-you in advance.

sharky_machine
Reply With Quote Quick reply to this message  
Join Date: Sep 2005
Posts: 133
Reputation: mawe is an unknown quantity at this point 
Solved Threads: 58
mawe mawe is offline Offline
Junior Poster

Re: Dictionary Sorting?

 
0
  #2
Dec 2nd, 2006
Hi!

Well ... a dict itself is not sorted (who would need this?)
  1. In [1]: d = {'a':1, 'b':2, 'c':3}
  2.  
  3. In [2]: d
  4. Out[2]: {'a': 1, 'c': 3, 'b': 2}
What you can do is sort the elements of a dict, but the result is no longer a
dict (which would be unsorted ... ):
  1. In [3]: ["%s => %s" % (key, d[key]) for key in sorted(d.keys())]
  2. Out[3]: ['a => 1', 'b => 2', 'c => 3']

Regards, mawe
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,141
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 948
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Dictionary Sorting?

 
0
  #3
Dec 2nd, 2006
Dictionaries are ultrafast lookup 'machines', also used by Python internally. In order to do the fast lookups the keys are hashed (digitized) and put into the dictionary in that order. The order is by hashed key, there is no sequential index lookup like in a list.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,564
Reputation: mattyd is an unknown quantity at this point 
Solved Threads: 1
Featured Poster
mattyd's Avatar
mattyd mattyd is offline Offline
Posting Maven

Re: Dictionary Sorting?

 
0
  #4
Dec 2nd, 2006
Originally Posted by vegaseat View Post
Dictionaries are ultrafast lookup 'machines', also used by Python internally. In order to do the fast lookups the keys are hashed (digitized) and put into the dictionary in that order. The order is by hashed key, there is no sequential index lookup like in a list.
Lists are mutable, Dictionaries are not. Besides this and the related speed issue that Python offers with dicts, are there other major issues between the two that would affect there uses? They are not the same thing, of course, which is obvious; it seems to me, at this point, that the keys used in dicts are a major advantage at least with what I am doing-- but then again, perhaps I am missing something.

I am not concerened with the speed at this point, only the ability to reference and manipulate the values within.

Thanks,

sharky_machine
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,221
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 138
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Dictionary Sorting?

 
0
  #5
Dec 2nd, 2006
Originally Posted by sharky_machine View Post
Lists are mutable, Dictionaries are not.
That is not true! Dictionaries are mutable! However, you cannot use mutable objects like lists and yes dictionaries for the key. Dictionary values can be most anything. Study some more and experiment with this interesting container. If you get stuck, ask more questions!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,564
Reputation: mattyd is an unknown quantity at this point 
Solved Threads: 1
Featured Poster
mattyd's Avatar
mattyd mattyd is offline Offline
Posting Maven

Re: Dictionary Sorting?

 
0
  #6
Dec 2nd, 2006
Originally Posted by bumsfeld View Post
That is not true! Dictionaries are mutable! However, you cannot use mutable objects like lists and yes dictionaries for the key. Dictionary values can be most anything. Study some more and experiment with this interesting container. If you get stuck, ask more questions!
Is it then the keys of the dictionary that are immutable? Not the entire dict? I have read about this much and many sources claim that Python dicts "are immutable." I just did a search again about dicts, and came upon a page that claims that "lists are immutable" :rolleyes: .

I think much of the on-line info is incorrect as much of it directly contadicts other sources and seems incomplete. It is difficult to find the truth. Frustrating.

Thanks for your earlier reply.

Regards,
sharky_machine
Reply With Quote Quick reply to this message  
Join Date: Apr 2006
Posts: 151
Reputation: ghostdog74 is on a distinguished road 
Solved Threads: 40
ghostdog74 ghostdog74 is offline Offline
Junior Poster

Re: Dictionary Sorting?

 
0
  #7
Dec 2nd, 2006
Originally Posted by sharky_machine View Post
Is it then the keys of the dictionary that are immutable? Not the entire dict? I have read about this much and many sources claim that Python dicts "are immutable." I just did a search again about dicts, and came upon a page that claims that "lists are immutable" :rolleyes: .

I think much of the on-line info is incorrect as much of it directly contadicts other sources and seems incomplete. It is difficult to find the truth. Frustrating.

Thanks for your earlier reply.

Regards,
sharky_machine
In Python docs first para here http://www.python.org/doc/2.4.1/lib/typesmapping.html

"""
2.3.8 Mapping Types -- classdict
A mapping object maps immutable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. A dictionary's keys are almost arbitrary values. Only values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.

"""
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Dictionary Sorting?

 
0
  #8
Dec 2nd, 2006
Actually, it's OK that dictionaries aren't sorted. The real thing that we sometimes want is to be able to access the values in a sorted manner.

Here's how:

  1. k = d.keys() # or, k = [x for x in d]
  2. k.sort()
  3.  
  4. for i in k:
  5. print d[i] # or my_func(d[i]) or whatever
Jeff

P.S. dictionaries *have* to be mutable; else, you could never add items to them! But the dictionary keys cannot be. I think the reason that they can't have mutable keys is that if you mutated a dictionary key, the hash table would get dorked up.
Last edited by jrcagle; Dec 2nd, 2006 at 11:23 pm. Reason: extra thought
Reply With Quote Quick reply to this message  
Join Date: Jul 2006
Posts: 608
Reputation: jrcagle is on a distinguished road 
Solved Threads: 150
jrcagle jrcagle is offline Offline
Practically a Master Poster

Re: Dictionary Sorting?

 
0
  #9
Dec 2nd, 2006
Originally Posted by sharky_machine View Post
Are there other major issues between the (lists and dicts) that would affect there uses?
Dictionaries are my current favorite data-type, for the simple reason that they allow you to express the types of coding thoughts that you want without having to keep careful track of indices.

Here's how I teach dictionaries: dictionaries are essentially lists whose indices are anything you want, instead of integers.

This is the ugly way, using lists:

  1. # my hero generator
  2.  
  3. attrs = []
  4.  
  5. attrs[0] = random.randint(1,20) # strength
  6. attrs[1] = random.randint(1,20) # wisdom
  7. attrs[2] = random.randint(1,20) # dexterity
  8. attrs[3] = random.randint(1,20) # intelligence
Any time I want to access strength, I have to remember -- or my code has to look up in a separate list -- the fact that strength is attrs[0]. Yuck, and quite error-prone.

With dictionaries, I can just do this:


  1. # my hero generator
  2.  
  3. attrs = {}
  4.  
  5. attrs['str'] = random.randint(1,20)
  6. attrs['wis'] = random.randint(1,20)
  7. attrs['dex'] = random.randint(1,20)
  8. attrs['int'] = random.randint(1,20)
now, if I want to know the strength of my character, I don't have to remember which index the 'str' attribute is ... I just ask,

print attrs['str']
15

and it's there. The dictionary allows me to encapsulate the 'looking up' details so that I can think about the big picture. Result: dramatic reduction in coding errors. Very cool.

Jeff
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the Python Forum


Views: 5856 | Replies: 8
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC