## Wednesday, October 24, 2012

### Map in python - and it's application to ini file reader

Mapping Types is a container that maps from an element to the other element. In python, map is implement in dict.

# Making a map(dirctionary) in python

Dictionary is represented as follows:
e = {"one": 1, "two": 2}

The two items are mapped with ":" charactore, and each mapping is separated by a comman. Python builds dict object with '{' and '}' character.

You can use dict() method to build one.
class dict(**kwarg)

You may not familiar with ** notation. This is a simple example used in python method.
def hello(**x):
print x

hello(x=1,y=2)

When you execute this code, you will get a dictionary object.
{'y': 2, 'x': 1}

When python method sees **something, all the assignments (x = 1, y = 2 in this example) given as a parameter is wrapped inside an automatically generated dictionary, and parameter variable x is pointing to the dictionary. In short, you can think of **something as collect (*) and make dictionary (*), and name it something.

As you see the meaning of **something as a parameter to the function. You'll see that this code will make the same dictionary as before.
a = dict(one=1, two=2)

You have more options to make the dictionary.
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)

For the first case, when first item is a mapping (other dictionary), it will build a new dictionary with the contents of it together with the additional parameters.
b = dict({'one': 1, 'two': 2})

For the next case, the first parameter can be a list with lists that has two elements.
c = dict(zip(('one', 'two'), (1, 2)))
d = dict([['two', 2], ['one', 1]])

zip method has two parameters, and iterate over the elements in each of the two elements to zip a list of list that contains two elements from each parameters.

Of course, you can add additional assignments so that they are added to the newly generated dictionary.

# Using dictionary

For getting all the items in a dictionary, you need to use items().
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
print d
print d.items()

{'orange': 2, 'pear': 1, 'banana': 3, 'apple': 4}
[('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)]