Dictionaries vs List data structures In Python

Suppose you have a following list:

>>> list = ['Booboo', 10, 'Orestis', 5, 'Homer', 7, 'Asterix', 9]
>>> list
['Booboo', 10, 'Orestis', 5, 'Homer', 7, 'Asterix', 9]

Booboo has 10, Orestis has 5, Homer has 7 and last but not least Asterix has 9. Now, I want to concatenate each pair. eg Booboo 10

>>> list[0] + list[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

Haaa, that’s a Type Error. You see, you cannot mix strings and numbers altogether in your salad.

Use the str() method  (not recommended)

You  can always make use of str() method which converts any number into a stirng, so basically str(10) means that 10 is not a number anymore but a string.

>>> list[0] + str(list[1])
'Booboo10'

Now if you want to add a space between these two, just concatenate the space like this:

>>> list[0] + ' ' + str(list[1])
'Booboo 10'

Use a dictionary instead of a list (recommended)

Using a dictionary is a more efficient and much more natural way to work with these data, because in this particular example it is like a key & value pair. So in other words if I want to retrieve a person’s number I will ask for the this person’s name.

>>> dict = {'Booboo':10, 'Orestis': 5, 'Hommer': 7, 'Asterix': 9}

>>> dict
{'Asterix': 9, 'Hommer': 7, 'Orestis': 5, 'Booboo': 10}

Note that the data returned not in the same order as the data entered. This is an important aspect of dictionaries. We don’t store data in the dictionaries because we are interested in their order (eg an alphabetic order). Now, we are only interested in a list of keys and in a list of values. Order doesn’t matter and it doesn’t make any difference. As I told you before, we are only interested to enter a name and retrieve its value number. Let’s verify that the system works:

>>> dict['Hommer']
7

Also remember if we are interested in what the keys are, we can use the keys() function.

>>> dict.keys()
['Asterix', 'Hommer', 'Orestis', 'Booboo']

Likewise we can use the values() function to return a list of values:

>>> dict.values()
[9, 7, 5, 10]

Calculate the average (easy way!)

Having such a function that returns the values as a list it would be useful if you were trying to compute the average, because it would be really easy to do it in one single line of code:

math.fsum(dict.values()) / len(dict)
7.75