Friday, August 28, 2009

Python 3.0 handles Dictionary differently

I read through Python 3.0 from Developer's Library about 2 months ago. I decided to skim through another introductory level book used at MIT so I could try keeping Python 2.5.x and Python 3.x separate.
While reading about Python 3.0, I didn't catch this difference. Dictionary processing has changed a little bit in the new version of Python.
For instance:
Python 2.5.x (pg 112 from MIT's reading material):
>>> letterCounts = {}
>>> for letter in "Mississippi":
letterCounts[letter] = letterCounts.get (letter, 0) + 1
>>> letterCounts
{’M’: 1, ’s’: 4, ’p’: 2, ’i’: 4}
>>> letterItems = letterCounts.items()
>>> letterItems.sort()
>>> print letterItems
[(’M’, 1), (’i’, 4), (’p’, 2), (’s’, 4)]
Python 3.1.x:
>>> letterCounts = {}
>>> for letter in "Mississippi":
letterCounts[letter] = letterCounts.get (letter, 0) + 1
>>> letterCounts
{'i': 4, 'p': 2, 's': 4, 'M': 1}
>>> letterItems = list(letterCounts.items())
>>> letterItems.sort()
>>> letterItems
[('M', 1), ('i', 4), ('p', 2), ('s', 4)]
This is a slight difference in code. In fact, the Python 3 code will work in previous versions. But, if you tried the Python 2.5.x code in Python 3, you will notice that letterItems can not be sorted. This is because "letterItems = letterCounts.items()" returns type: <class 'dict_items'>
An explanation of what is going on can be found here.
"Python 3.0 changes keys(), values() and items() so they return a lightweight set-like object, effectively making them behave like the olditer* methods, and removed the iter* methods themselves. In Python 3.0"

No comments:

Archive