I first learned python at version 1.4 or so, and I am supporting python code that was also written around that time.
Since Python 1.5 there have been many improvements to the language, and I have religiously read the release notes of every new release in an attempt to stay up to date. My success was mixed, and I occasionally come across better ways to do things that were introduced in later Python releases, that passed me by somehow.
I plan to share them with you here….
Lets start with the ubiquitous dict
Dictionaries are wonderful things that can be used in all sorts of ways. Having a built a dictionary of values though, you will eventually need to retrieve data from it. Here is the first trap for an older user, I always want to write something like:
if dictionary.has_key(key):
data = dictionary[key]
….
This has of course been superseded and nowadays one writes:
if key in dictionary:
data = dictionary[key]
….
Note that if you want to return a default value if the key is not in the dict, you can use the get() method.
When iterating over a dictionary it’s a similar story:
for key in dictionary.keys():
…..
has been improved an you can use:
for key in dictionary:
……..
Naturally if you want to change the dictionary inside the for loop, you will have to use the keys() method to obtain a list to iterate over, just like in the old days!
I hope you found that useful …