| | |
Dictionary Sorting?
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
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
Any, advice, suggestions, or direction would be greatly appreciated.
Thank-you in advance.
sharky_machine
•
•
Join Date: Sep 2005
Posts: 133
Reputation:
Solved Threads: 58
Hi!
Well ... a dict itself is not sorted (who would need this?)
What you can do is sort the elements of a dict, but the result is no longer a
dict (which would be unsorted ...
):
Regards, mawe
Well ... a dict itself is not sorted (who would need this?)
Python Syntax (Toggle Plain Text)
In [1]: d = {'a':1, 'b':2, 'c':3} In [2]: d Out[2]: {'a': 1, 'c': 3, 'b': 2}
dict (which would be unsorted ...
): Python Syntax (Toggle Plain Text)
In [3]: ["%s => %s" % (key, d[key]) for key in sorted(d.keys())] Out[3]: ['a => 1', 'b => 2', 'c => 3']
Regards, mawe
•
•
•
•
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.
I am not concerened with the speed at this point, only the ability to reference and manipulate the values within.
Thanks,
sharky_machine
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!
•
•
•
•
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!
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
•
•
Join Date: Apr 2006
Posts: 151
Reputation:
Solved Threads: 40
•
•
•
•
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
"""
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.
"""
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
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:
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.
Here's how:
Python Syntax (Toggle Plain Text)
k = d.keys() # or, k = [x for x in d] k.sort() for i in k: print d[i] # or my_func(d[i]) or whatever
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
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
•
•
•
•
Are there other major issues between the (lists and dicts) that would affect there uses?
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)
# my hero generator attrs = [] attrs[0] = random.randint(1,20) # strength attrs[1] = random.randint(1,20) # wisdom attrs[2] = random.randint(1,20) # dexterity attrs[3] = random.randint(1,20) # intelligence
With dictionaries, I can just do this:
Python Syntax (Toggle Plain Text)
# my hero generator attrs = {} attrs['str'] = random.randint(1,20) attrs['wis'] = random.randint(1,20) attrs['dex'] = random.randint(1,20) attrs['int'] = random.randint(1,20)
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
![]() |
Similar Threads
- Dictionary Keys (Python)
Other Threads in the Python Forum
- Previous Thread: Another List if statment
- Next Thread: IP2Location Python Library
Views: 5856 | Replies: 8
| Thread Tools | Search this Thread |
Tag cloud for Python
anti array avogadro beginner builtin clear client code color count csv curved def dictionary dynamic enter examples excel file float format frange ftp function gui heads hints homework import input java lapse line lines linux list lists loop microcontroller mouse multiple mysqldb mysqlquery newb number numbers output parsing path port prime program programming projects py2exe pygame pyopengl pyqt python random raw_input recursion recursive redirect script scrolledtext singleton software sqlite ssh stderr string strings subprocess sum syntax table terminal text thread threading time tkinter tlapse tooltip tuple tutorial twoup ubuntu unicode unix urllib urllib2 variable web-scrape wikipedia windows word wx.wizard wxpython






