Coding Curriculum - Python

Basic Concept of Dictionary

A Python dictionary is also called associative arrays or hash tables. It is a container type that is able to store values, strings and any other Python objects. It exists as a pair of keys and the corresponding value for the key.

Example 1:

dictFavourate = {'fruit': 'banana' , 'sport': 'football' , 'person': 'myself'}

In this case, 'fruit' 'sport' 'person' are keys of this dictionary, and 'banana' 'football' 'myself' are the strings corresponding to the keys. And you can use a different way to make a dictionary.

Example 2:

dictFavourate ['fruit'] = 'apple'

'fruit' is the key in this example, and 'apple' is the string corresponding to the key 'fruit'.

And you can check the keys in the Python shell after running the code by typing in **dictFavourate.keys()** in this case.

And the keys for **dictFacourate** will be shown on the shell as below:

Example 3:

>>> dictFavourate.keys()
['person', 'fruit', 'sport']

Sometimes, we need to create a set of dictionary to store the keys and values.

For example, if you want to write a love letter to someone you want to chase, but in a gentle and implicit way. You can use a series of numbers to present words ( '1' stands for 'a', '2' stands for 'b',etc. ). In this case we can create a dictionary to convert integers to letters.

So "I l o v e u" can be present by series of numbers we can store "iloveu" into a dictionary so its totally 6 keys and 6 correspond letters.

Example 4:

converter = {
'5':'e',
'9':'i',
'12':'l',
'15':'o',
'21':'u',
'22':'v'
}
for keys in ['9','12','15','22','5','21']:
print(converter[keys])

The code above is to store the keys and values into 'converter'. And we need to figure out how to output this message. The correct order of the integers correspond to the word "I l o v e u" is [9,12,15,22,5,21], so we need to print it out. In order to avoid a newline after print a letter, we should add , after print function.