Main Content

Python dictionaries - mutable and immutable keys and values

Archive - Originally posted on "The Horse's Mouth" - 2011-01-29 09:38:45 - Graham Ellis

Lists, Tuples, and dictionaries are the conventional collection variables in Python - but when you stop to consider it, objects and strings are collections too. All of these structures bundle together other elements (members) in various ways.

In first dictionary demonstrations, we usually use strings as both the key and the value; strings can be quickly set up so the demos are short, and strings are far and away the most common keys anyway. There's such a first example from our training notes [here], and an example that goes a lot further in accessing / sorting all the elements (you can't sort a dictionary, but you can sort the keys!) [here].

During yesterday's Python course in Oxford, I set (and later answered) an exercise that created a dictionary of objects, keyed on a string - the code is [here]. That's a very common use indeed of a dictionary, where a whole series of things (objects) is reference by some sort of unique string - a "primary key" in database terms.

A further example, in which the keys are other objects, may be found [here], with the class that's used as keys defined in a separate file [here]. You'll note that we've added two objects set up with identical parameters as keys, and they have formed separate members of the dictionary. That's because objects of our type coin are "muttable" - i.e. changeable, as opposed to strings which are not changeable in situ - "immutable"; if you use the same immutable key twice, you'll be referring to one and the same object and the second one added will overwrite the first.

More about mutable and immutable on my next Python courses - you may have missed Oxford this week, and the course in Frankfurt in 2 weeks time is private (single company) one. But we do have a public course coming up in about a month. See Learning to Program in Python and Python Programming.