mmmm Interesting

September 8, 2008

Keep on running …

Filed under: Python — e078120 @ 10:59 am

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 …

1 Comment »

  1. Hi Roger,

    nice to hear from you again. I guess you’re puzzling who I am. Here’s a clue: I left Munich about 2 1/2 years ago and at that time you were a collegue of me.

    Now back to the dictionaries. I have seen they released Python 2.6 and even a 3.1 beta is already available. What a progress! As you pointed out you can use dictionaries in a quite natural language style. You lucky one! I have to fight VBA with all its awkward snytax. They don’t even have an associative array!

    Well, you could use something that is named “dictionary” but you can’t tell if a key is already used. If you do so, you’ll get an exception. Really ugly, isn’t it?

    So stay with Python as long as you can. It is really a well made computer language.

    Best regards from Luxembourg,

    Christian

    Comment by Christian — May 28, 2009 @ 2:35 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.