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

Recommended Answers

All 8 Replies

Hi!

Well ... a dict itself is not sorted (who would need this?)

In [1]: d = {'a':1, 'b':2, 'c':3}

In [2]: d
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 ... ;)):

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.

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

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!

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

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.

"""

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:

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

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.

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:

# 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

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:

# 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)

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
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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.