944,144 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 7952
  • Python RSS
Dec 2nd, 2006
0

Dictionary Sorting?

Expand Post »
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
Similar Threads
Featured Poster
Reputation Points: 105
Solved Threads: 1
Posting Maven
mattyd is offline Offline
2,582 posts
since Oct 2006
Dec 2nd, 2006
0

Re: Dictionary Sorting?

Hi!

Well ... a dict itself is not sorted (who would need this?)
Python Syntax (Toggle Plain Text)
  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 ... ):
Python Syntax (Toggle Plain Text)
  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
Reputation Points: 19
Solved Threads: 58
Junior Poster
mawe is offline Offline
133 posts
since Sep 2005
Dec 2nd, 2006
0

Re: Dictionary Sorting?

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.
Moderator
Reputation Points: 1333
Solved Threads: 1404
DaniWeb's Hypocrite
vegaseat is offline Offline
5,792 posts
since Oct 2004
Dec 2nd, 2006
0

Re: Dictionary Sorting?

Click to Expand / Collapse  Quote originally posted by vegaseat ...
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
Featured Poster
Reputation Points: 105
Solved Threads: 1
Posting Maven
mattyd is offline Offline
2,582 posts
since Oct 2006
Dec 2nd, 2006
0

Re: Dictionary Sorting?

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!
Reputation Points: 404
Solved Threads: 180
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Dec 2nd, 2006
0

Re: Dictionary Sorting?

Click to Expand / Collapse  Quote originally posted by bumsfeld ...
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
Featured Poster
Reputation Points: 105
Solved Threads: 1
Posting Maven
mattyd is offline Offline
2,582 posts
since Oct 2006
Dec 2nd, 2006
0

Re: Dictionary Sorting?

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.

"""
Reputation Points: 75
Solved Threads: 44
Junior Poster
ghostdog74 is offline Offline
156 posts
since Apr 2006
Dec 2nd, 2006
0

Re: Dictionary Sorting?

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:

Python Syntax (Toggle Plain Text)
  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
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006
Dec 2nd, 2006
0

Re: Dictionary Sorting?

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:

Python Syntax (Toggle Plain Text)
  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:


Python Syntax (Toggle Plain Text)
  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
Reputation Points: 92
Solved Threads: 156
Practically a Master Poster
jrcagle is offline Offline
608 posts
since Jul 2006

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: Another List if statment
Next Thread in Python Forum Timeline: IP2Location Python Library





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC