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. You can use the for loop to loop through a dictionary, e.g.:


 

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

Output:

or

Output:

 

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

 

8. 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:


 

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

 

Exercise 4

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

Sample solution:

 

Exercise 5

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

Sample solution:

 

Exercise 6

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

Sample solution:

 

Exercise 7

What will happen when you run the following code?

 

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

 

Exercise 8

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. 9

What is the output of the following code snippet?

 

Correct answer

2

Ex.10

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. 11

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. 12

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. 13

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. 14

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']