Abdullah Diab’s Blog

I’m Learning Python part 6

I’m Learning Python (part 6)

<p>
  <img title="Python Logo" src="http://www.python.org/images/python-logo.gif" alt="Python Logo" />
</p>

Dictionaries

Dictionaries in Python are like dictionaries in life, they consist of key-value pairs, each key maps a value, values can be any object type, and keys also. Keys must be unique, I mean that we can’t have two identical keys with different values.

Dictionaries are defined using curly braces { and } as the following:
>>> D = {‘name’ : ‘Abd Allah Diab’, ‘age’ : 19, ‘job’ : ‘Web Developer’}
Now we can access any of the pairs using only the key:
>>> D[‘age’]
19
Dictionaries are mutable objects, which means we can change their values in place:
>>> D[‘age’] += 1
>>> D[‘age’]
20
We can add new pairs also easily:
>>> D[‘eyes’] = ‘brown’
>>> D
{‘job’ : ‘Web Developer’, ‘age’ : 20′, ‘eyes’ : ‘brown’, ‘name’ : ‘Abd Allah Diab’}
As you can see, the dictionary is not sorted, we entered the name first then the age and job, and at last we added the eyes, but it prints in a different order.
To sort a dictionary you should sort its keys and then print the values of the keys after sorting like the following:
>>> keys = D.keys()
>>> keys [‘job’, ‘age’, ‘eyes’, ‘name’]
>>> keys.sort()
>>> keys
[‘age’, ‘eyes’, ‘job’, ‘name’]
>>> for key in keys:
print key, ‘=>’, D[key]
age => 20
eyes => brown
job => Web Developer
name => Abd Allah Diab
Here we used a for loop which I haven’t covered, but it is just like list comprehensions, it will do what follows its declaration for each member of the set (here keys).
Please notice the indentation, after the for declaration you must hit the ‘tab’ for each line inside the for loop, and to exit the loop just don’t hit the ‘tab’ (press ‘enter’ in interactive mode).
You can make use of a new method called ‘sorted’ which takes any iteratable object (like a sequence or a string etc):
>>> for key in sorted(D)
print key, ‘=>’, D[key]
age => 20
eyes => brown
job => Web Developer
name => Abd Allah Diab

Nesting

As I told you @ first, the values can be any object, so we can nest anything inside dictionaries, for example if I want to store the first name and last name inside the ‘name’ in the dictionary, and to save a list of jobs inside the ‘job’ in the dictionary, I’d do that just like I nested matrices last time:
>>> D = {‘name’ : {‘first’ : ‘Abd Allah’, ‘last’ : ‘Diab’}, ‘age’ : 19, ‘job’ : [‘Web Developer’, ‘Teacher’, ‘Student’]}
Now let’s see how we can access what we’ve built:
>>> D[‘name’]
{‘first’ : ‘Abd Allah’, ‘last’ : ‘Diab’}
>>> D[‘name’][‘first’]
‘Abd Allah’
>>> D[‘name’][‘last’]
‘Diab’
>>> D[‘job’]
[‘Web Developer’, ‘Teacher’, ‘Student’]
>>> D[‘job’][0]
‘Web Developer’
>>> D[‘job’][-1]
‘Student’
Pretty easy right? 🙂

Memory issue

Did you ask yourself where did the old D dictionary go?
In C, C++ and many other old languages you had to manage memory by hand, but in advanced languages like Java, .NET and Python there exists a garbage collector which handles this process for you, whenever you an object has no references the garbage collector will deallocate its space.

Missing keys

When accessing a dictionary you should be careful to missing keys, especially when the dictionary is filled dynamically.
Accessing a missing key will be a mistake:
>>> D[‘FFF’] #Will give you a key error.
To avoid this mistake you can ask the dictionary if it has the key then you can access it:
>>> if not D.has_key(‘fff’):
print ‘MISS’
MISS
Here we used the if control, which takes this form:
if :
Block1
elif :
Block2
.
.
elif :
BlockN
else:
Block
Notice the indentation, ‘cuz in Python the scope is defined using indention not curly braces or Begin and End.

For Loops, List Comprehensions and Performance

Every list comprehension can be done using a for loop instead:
>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]
>>> squares
[1, 4, 9, 16, 25]
Can be done:
>>> squares = []
>>> for x in [1, 2, 3, 4, 5]
squares.append(x ** 2)
>>> squares
[1, 4, 9, 16, 25]
But the former is faster than the latter (sometimes it is twice faster), that’s because Python is optimized, and every new version is faster and optimized more than old ones.
So the rule in Python is “Code for simplicity and readability firs, and worry about performance later” but in most cases you will stop after writing a readable program, ‘cuz Python is optimized by itself.

Tuples

Tuples (pronounced ‘tooples’) are just like lists but they are immutable, which mean that they can’t be changed once the are created, but like strings support type methods (split, len, …) and nesting and sequence operations.
Tuples are defined in parentheses ( ):
>>> T = (1, 2, 3, 4)
>>> T
(1, 2, 3, 4)
>>> T[2]
3
>>> T[-1]
4
>>> T = T + (5, 6, 7)
>>> T
(1, 2, 3, 4, 5, 7)
You might wonder, why would I use an immutable list when I can use a list? The answer is that sometimes you might want to call a method with a list parameter which you don’t want it to be changed, or when you send lists through your program and you don’t want them to be changed, you’ll use tuples then.

Other File Types

Those types we discussed aren’t the only types, there exist more types, such as sets, which are like mathematical sets (a container for a list of objects):
>>> X = set([1, 2, 3, 4])
>>> X set([1, 2, 3, 4])
>>> X.add(5)
>>> X
set([1, 2, 3, 4, 5])
>>> Y = set([1, 6, 3])
>>> X & Y #Intersection
set([1, 3])
>>> X | Y #Union
set([1, 2, 3, 4, 5, 6])
>>> X – Y #Difference
set([2, 4, 5])
Python also supports lots of types, but we won’t cover them all here (or at least now :)).

User-defined Types

You can build your own classes in Python:
>>> class Man:
def __intit__(self, name, age): #Constructor which takes two parameters and saves them
self.name = name #self is the object that we’re calling the method on.
self.age = age
def lastname(self): #A method to get the last name of the man.
return self.name.split(‘ ‘)[-1]
Now you can use your class:
>>> me = Man(‘Abd Allah Diab’, 19) #Initialize a new instance of Man
>>> me.lastname()
‘Diab’
>>> me.age
19
We won’t discuss classes and objects here, but I wanted to show you that you can have your own type easily.

Bottom Line

Here we come to the end of our tour on built in primitive types of Python, Next time we’ll start our detailed trip to Numbers 🙂
Until then keep coding and make mistakes, and don’t forget to learn of your mistakes 😀
Cheers.