Dictionaries in Python

1. Dictionaries are unordered*, changeable (mutable), and indexed collections of data. (*In Python 3.6x dictionaries have become ordered by default.

Each dictionary is a set of key: value pairs. You can create it by using the following syntax:


 

2. If you want to access a dictionary item, you can do so by making a reference to its key inside a pair of square brackets (ex. 1) or by using the get() method (ex. 2):


 

3. If you want to change the value associated with a specific key, you can do so by referring to the item’s key name in the following way:

 

4. To add or remove a key (and the associated value), use the following syntax:


You can also insert an item to a dictionary by using the update() method, and remove the last element by using the popitem() method, e.g.:


 

5. Loop through a keys of the dictionary, e.g.:


zamek
woda
gleba

or


zamek
woda
gleba

7.  Loop through a dictionary’s values

castle
water
soli

or

castle
water
soli

 

6. If you want to loop through a dictionary’s keys and values, you can use the items() method, e.g.:

('zamek', 'castle')
('woda', 'water')
('gleba', 'soil')

or

zamek : castle
woda : water
gleba : soil

 

8. To check if a given key exists in a dictionary, you can use the in keyword:

 

9. You can use the del keyword to remove a specific item, or delete a dictionary. To remove all the dictionary’s items, you need to use the clear() method:


 

10. To copy a dictionary, use the copy() method:

 

Exercise 1

Write a program that will “glue” the two dictionaries (d1 and d2) together and create a new one (d3).

Sample solution:

 

Exercise 2

Write a program that will convert the my_list list to a tuple.

Sample solution:

 

Exercise 3

Write a program that will convert the colors tuple to a dictionary.

Sample solution:

 

Exercise 4

What will happen when you run the following code?

 

The program will print {'A': 1, 'B': 2} to the screen.

 

Exercise 5

What is the output of the following program?

 

white : (255, 255, 255)

grey : (128, 128, 128)

red : (255, 0, 0)

green : (0, 128, 0)

 

Ex. 6

What is the output of the following code snippet?

 

Correct answer

2

Ex. 7

Which of the following statements correctly creates a list?

(Select two answers)

lst3 = list('a', 'b')

lst2 = 1, 2, 3

lst4 = list(('a', 'b'))

lst1 = [1, 2, 2, '3', [4, 5]]

 

Ex. 8

Given the code snippet below, what statement should you insert in place of the comment line to get the following output:

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}?

d1 = d1 + d2

d1.insert(d2)

d1.update(d2)

d1.append(d2)

 

Ex. 9

Which of the following dictionaries are created correctly?

(Select two answers)

d2 = {[1, 2]: 1, [3, 4]: 3}

d4 = {'Mary': 30, 'Robert': 28}

d3 = {'y': 1, 'x': 10, 'x': 100}

d1 = {}

 

Ex. 10

What is the output of the following code snippet?

{1: 'c', 3: 'a', 5: 'b', 7: 'd'}

[1, 3, 5, 7]

(1, 3, 5, 7)

1, 3, 5, 7

 

Ex. 11

Consider the following dictionary:

Which of the following statements removes the element with the key 'c' from the d dictionary?

(Select two answers)

d.remove('c')

d.del('c')

d.pop('c')

del d['c']

 

Ex. 12

What is the expected output of the following snippet ?

Explanation:

The l variable is an empty dictionary initially.

The for loop populates the dictionary with the characters from the string ‘Skywalker” that are in the string ‘Vader’ (i.e. a, e and r) : those are the values of the dictionary while the corresponding keys are the Unicode code of the corresponding character (the ord() function returns the Unicode code of a character).

In a for-else loop, the else: clause is executed when the code below the for loop has completed successfully – in this case the code in the else: clause adds the following key:value pair to the dictionary : 100:'d'.

So by the end of the first for-else loop, the l dictionary is as follow:

{97: 'a', 101: 'e', 114: 'r', 100: 'd'}

The last for loop, simply print each value from the l dictionary using the end parameter of the print() function to have the characters nicely printed on one line, separated by a space.

Resulting output is :

a e r d

 

Ex. 13

What is the output of the following snippet ?

A: [97, 98, 99, 100]

B: [100, 99, 98, 97]

C: [98, 99, 100, 97]

D: ['a', 'b', 'c', 'd']

Explanation:

my_list is a dictionary (the poorly chosen name was selected to confuse you).

The ord() function returns the Unicode code from a given character. So my_list is a dictionary that looks like this :

{'a': 97, 'b': 98, 'c': 99, 'd': 100}

my_list.keys() will return a view object that displays the list of all the keys of the dictionary (in this case : dict_keys(['a', 'b', 'c', 'd')]).

The for loop will iterate over each of those keys and my_list[i] will be the value from the dictionary for the corresponding key ( for example : my_list['a'] –> 97). So the for loop will simply insert each value from the dictionary in the list list using the insert() method.

The  insert() method inserts a given element at a given index in a list. The syntax is :

list_name.insert(index, element).

In this case, index = -1 ; pay particular attention to the behavior of the insert() method in this case – see print out below for details.

Try it yourself:

C.

 

Ex. 14

What code would you insert instead of the comment to obtain the expected output ?

Expected output :

Code :

A. print(j[0])

B. print(j)

C. print(j[i])

D. print(j['0'])