Dictionary Case Study - GKTCS

Dictionary Case Study

1

A Python dictionary is mutable and container type can store any number of python object

Python dictionaries are also known as associative arrays or (#) tables. Dictionaries consists of pair (items) of keys and their corresponding

values. The general syntax of dictionary is as follows:

dict={`A':'2', `B':'73', `C':'32'}

2

One way to create a dictionary is to start with the empty dictionary and add key-value pairs. The empty dictionary is denoted {}. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can't be repeated and must be immutable.

As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the keys are strings.

>>> dict = {} >>> dict['one'] = 'uno' >>> dict['two'] = 'dos'

The first assignment creates a dictionary named dict; the other assignments add new key-value pairs to the dictionary.

3

We can print the current value of the dictionary in the usual way: >>> print dict {'two': 'dos', 'one': 'uno'}

The key-value pairs of the dictionary are seperated by commas. Each pair contains a key and a value separated by a colon. The order of the pairs may not be what you expected. Python uses complex algorithms to determine where the key-value pairs are stored in a dictionary. For our purposes we can think of this ordering as unpredictable.

4

Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output:

>>> dict = {'one': 'uno', 'two': 'dos', 'three': 'tres'} It doesn't matter what order we write the pairs. The values in a dictionary are accessed with keys, not with indices, so there is no need to care about ordering.

5

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download