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:
|
1 2 3 4 5 |
my_dictionary = { key1: value1, key2: value2, key3: value3, } |
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):
|
1 2 3 4 5 6 7 8 9 10 11 |
pol_eng = { "kwiat": "flower", "woda": "water", "gleba": "soil" } item_1 = pol_eng["gleba"] # ex. 1 print(item_1) # outputs: soil item_2 = pol_eng.get("woda") print(item_2) # outputs: water |
|
1 2 3 4 5 6 7 8 9 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } pol_eng["zamek"] = "lock" item = pol_eng["zamek"] print(item) # outputs: lock |
4. To add or remove a key (and the associated value), use the following syntax:
|
1 2 3 4 5 6 7 |
phonebook = {} # an empty dictionary phonebook["Adam"] = 3456783958 # create/add a key-value pair print(phonebook) # outputs: {'Adam': 3456783958} del phonebook["Adam"] print(phonebook) # outputs: {} |
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.:
|
1 2 3 4 5 6 7 |
pol_eng = {"kwiat": "flower"} pol_eng.update({"gleba": "soil"}) print(pol_eng) # outputs: {'kwiat': 'flower', 'gleba': 'soil'} pol_eng.popitem() print(pol_eng) # outputs: {'kwiat': 'flower'} |
5. Loop through a keys of the dictionary, e.g.:
|
1 2 3 4 5 6 7 8 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } for k in pol_eng: print(k) |
zamekwodagleba
or
|
1 2 3 4 5 6 7 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } for k in pol_eng.keys(): print(k) |
zamekwodagleba
7. Loop through a dictionary’s values
|
1 2 3 4 5 6 7 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } for v in pol_eng.values(): print(v) |
castle
water
soli
or
|
1 2 3 4 5 6 7 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } for i in pol_eng.keys(): print(pol_eng[i]) |
castle
water
soli
6. If you want to loop through a dictionary’s keys and values, you can use the items() method, e.g.:
|
1 2 3 4 5 6 7 8 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } for value in pol_eng.items(): print(value) |
('zamek', 'castle')
('woda', 'water')
('gleba', 'soil')
or
|
1 2 3 4 5 6 7 8 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } for k, v in pol_eng.items(): print(k, ":", v) |
zamek : castle
woda : water
gleba : soil
8. To check if a given key exists in a dictionary, you can use the in keyword:
|
1 2 3 4 5 6 7 8 9 10 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } if "zamek" in pol_eng: print("Yes") else: print("No") |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } print(len(pol_eng)) # outputs: 3 del pol_eng["zamek"] # remove an item print(len(pol_eng)) # outputs: 2 pol_eng.clear() # removes all the items print(len(pol_eng)) # outputs: 0 del pol_eng # removes the dictionary |
10. To copy a dictionary, use the copy() method:
|
1 2 3 4 5 6 7 |
pol_eng = { "zamek": "castle", "woda": "water", "gleba": "soil" } copy_dictionary = pol_eng.copy() |
Exercise 1
Write a program that will “glue” the two dictionaries (d1 and d2) together and create a new one (d3).
|
1 2 3 4 5 6 |
d1 = {'Adam Smith': 'A', 'Judy Paxton': 'B+'} d2 = {'Mary Louis': 'A', 'Patrick White': 'C'} d3 = {} for item in (d1, d2): # Write your code here. print(d3) |
Sample solution:
|
1 2 3 4 5 6 7 8 |
d1 = {'Adam Smith': 'A', 'Judy Paxton': 'B+'} d2 = {'Mary Louis': 'A', 'Patrick White': 'C'} d3 = {} for item in (d1, d2): d3.update(item) print(d3) |
Exercise 2
Write a program that will convert the my_list list to a tuple.
|
1 2 3 4 |
my_list = ["car", "Ford", "flower", "Tulip"] t = # Write your code here. print(t) |
Sample solution:
|
1 2 3 4 |
my_list = ["car", "Ford", "flower", "Tulip"] t = tuple(my_list) print(t) |
Exercise 3
Write a program that will convert the colors tuple to a dictionary.
|
1 2 3 4 |
colors = (("green", "#008000"), ("blue", "#0000FF")) # Write your code here. print(colors_dictionary) |
Sample solution:
|
1 2 3 4 |
colors = (("green", "#008000"), ("blue", "#0000FF")) colors_dictionary = dict(colors) print(colors_dictionary) |
Exercise 4
What will happen when you run the following code?
|
1 2 3 4 5 |
my_dictionary = {"A": 1, "B": 2} copy_my_dictionary = my_dictionary.copy() my_dictionary.clear() print(copy_my_dictionary) |
The program will print {'A': 1, 'B': 2} to the screen.
Exercise 5
What is the output of the following program?
|
1 2 3 4 5 6 7 8 9 |
colors = { "white": (255, 255, 255), "grey": (128, 128, 128), "red": (255, 0, 0), "green": (0, 128, 0) } for col, rgb in colors.items(): print(col, ":", rgb) |
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?
|
1 2 |
d = {'c': 3, 'a': 1, 'a': 5, 'a': 2} print(d['a']) |
Which of the following statements correctly creates a list?
(Select two answers)
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'}?
|
1 2 3 4 5 6 |
d1 = {1: 'one', 2: 'two'} d2 = {3: 'three', 4: 'four'} # Insert code here print(d1) |
Ex. 9
Which of the following dictionaries are created correctly?
(Select two answers)
Ex. 10
What is the output of the following code snippet?
|
1 2 |
d = {3: 'a', 5: 'b', 1: 'c', 7: 'd'} print(sorted(d)) |
Ex. 11
Consider the following dictionary:
|
1 |
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}. |
Which of the following statements removes the element with the key 'c' from the d dictionary?
(Select two answers)
Ex. 12
What is the expected output of the following snippet ?
|
1 2 3 4 5 6 7 8 9 |
l={} for i in 'Skywalker': if i in 'Vader': l[ord(i)]=i else: l[ord('d')]='d' for j in l.keys(): print(l[j], end=' ') |
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 ?
|
1 2 3 4 5 6 |
my_list = {'a': ord('a'), 'b': ord('b'), 'c': ord('c'), 'd': ord('d') } list=[] for i in sorted(my_list.keys()): list.insert(-1,my_list[i]) print(list) |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
my_list = {'a': ord('a'), 'b': ord('b'), 'c': ord('c'), 'd': ord('d') } print(my_list) list=[] for i in sorted(my_list.keys()): print(my_list[i]) list.insert(-1,my_list[i]) print(list) print(list) # Following output will be printed : #{'a': 97, 'b': 98, 'c': 99, 'd': 100} #97 #[97] #98 #[98, 97] #99 #[98, 99, 97] #100 #[98, 99, 100, 97] #[98, 99, 100, 97] |
C.
Ex. 14
What code would you insert instead of the comment to obtain the expected output ?
Expected output :
|
1 2 3 |
Luke Han Leia |
Code :
|
1 2 3 4 5 6 7 8 9 |
my_dict = {} my_list = ['Luke', 'Han', 'Leia', 'Ben'] for i in range(len(my_list)-1): my_dict[i] = (my_list[i], ) for i in sorted(my_dict.keys()): j = my_dict[i] # Insert your code here |
A. print(j[0])
print(j)C. print(j[i])
D. print(j['0'])


