b83d509985036b188fee2f03ac32b7a4
python
lab6
v3
rasb14
2018-10-12 08:42:17
v3.1.3 (2018-09-13)

Generated 2018-10-12 10:42:17 by dbwebb lab-utility v3.1.3 (2018-09-13).


Lab 6 - python

A look into dictionaries and tuples.

1. Dictionaries

Some basics with dictionaries.

Exercise 1.1 (1 points)

Create a small phonebook using a dictionary. Use the names as keys and numbers as values.

Use

Baggins, Aragorn, Smaug

and corresponding numbers

55523412, 55564222, 55567894

Add the phonenumbers as integers. Answer with the resulting dictionary.

Exercise 1.2 (1 points)

How many items are there in the phonebook dictionary?

Exercise 1.3 (1 points)

Use the get() method on your phonebook and answer with the phonenumber of ‘Baggins’.

Exercise 1.4 (1 points)

Get all keys from the phonebook dictionary and return them in a sorted list.

Exercise 1.5 (1 points)

Get all values from the phonebook dictionary and return them in a sorted list.

Exercise 1.6 (1 points)

Use the in-operator to test if the name ‘Baggins’ exists in the phonebook dictionary. Answer with the return boolean value.

Exercise 1.7 (1 points)

Create a copy of the phonebook dictionary. Get and remove the item ‘Baggins’ from the copied phonebook (use pop()). Answer with the resulting dictionary.

2. Tuples

Some basics with tuples.

Exercise 2.1 (1 points)

Create a tuple with ‘moose, 12, 1.98, table, 7’. Answer with the length of the tuple as an integer.

Exercise 2.2 (1 points)

Create a tuple out of:

(moose, 12, 1.98, table, 7).

Assign each value in the tuple to different variables:

‘a’,’b’,’c’,’d’,’e’.

Answer with the variable: ‘d’.

Exercise 2.3 (1 points)

Use the list

[98, 5, 12, 369, 1]

Assign the first two elements to a tuple with a slice on the list.

Answer with the first element in the tuple as an integer.

Exercise 2.4 (1 points)

Create a tuple with

(elephant, 33, 7.28, stove, 4)

Convert it to a list and replace the second element with:

“cow”

Convert it back to a tuple and answer with the first three elements in a comma-separated string, without an ending ,.

3. Extra assignments

These questions are worth 3 points each. Solve them for extra points.

Exercise 3.1 (3 points)

Use a for-loop to walk through the original phonebook dictionary and create a string representing it. Each name and number should be on its own row, separated by a space. The names must come in alphabetical order. Note that every row should end with a newline character, \n.

Answer with the resulting string.

Exercise 3.2 (3 points)

Convert the phonenumber to a string and add the prefix ‘+1-‘, representing the language code, to each phone-number.

Answer with the resulting dictionary.


b83d509985036b188fee2f03ac32b7a4