Data type: dictionary & if

Objectives

a In other programming langauges a dictionary is named »Associative array«, in Python it is named »Dictionary«. Some useful methods and scenarios are demonstrated.

Instructions

Tasks:
  1. Create a script: dictionaries.py
  2. Create a second version of the refrigerator example according to the station for data type lists.
  3. Expand the mushroom example and generate a complete HTML page with print function.

Properties of a dictionary

  • Dictionaries are called mapping-type.
  • They are similar to the associative array of other programming languages.
  • They are represented by a pair of curly brackets {} and always contain name/value pairs that are separated by a colon. Names are also called keys
  • The order of the key values ​​in the dictionary is random.

Examples

cars = {'BMW':'Germany', 'Renault':'France', 'Volvo':'Sweden'}

# other stucture...

cars = {'BMW':'Germany',
        'Renault':'France',
        'Volvo':'Sweden'}
Method Note Example, comment
clear() removes all entries from a dictionary

cars.clear()

the result os an empty dictionary {}

copy() copy all entries af a give dictionary copy_of_cars = cars.copy()
has_key() returns the value 1 if the key exists if not 0 cars.has_key(‘Volvo’)
items() returns all name/value pairs each as a tuple cars.items()
keys() returns a list of all keys cars.keys() |
update() add a new name/value, if the key exists the value will be replaced cars[‘Skoda’] = ‘Czech Republic’
get() return the value to a give name

cars.get(‘Volvo’)

cars.get(‘xyz’,’???’)

Second Example

# create a dictionary...

mushrooms = {} # empty dictionary
mushrooms['cep'] = ['eatable x times', "mixed forest", "Boletus edulis"]
mushrooms['fly amanita'] = ["eatable once", "coniferous forest", "Amanita muscaria"]
mushrooms['bay bolete'] = ["eatable x times", "mixed forest", "Boletus badius"]
mushrooms['Coprinus'] = ['eatable x times', "meadow", "Coprinus"]

# print the content:

print('''Pretty print dictionary of mushrooms:\n ''')

for i in mushrooms.keys():
    print("""kind = {}, eatable = {}, be found = {}; """.format(i,
                                                                mushrooms[i][0],
                                                                mushrooms[i][1]))

In this example some other data types are used or created.

  • Dictionary = mushrooms
  • List = as result of the mehtod call keys()
  • Tupel = as parameter of the format method

Many more variations are possible eg. combined with a Slicing -operator.