Python
Intermediate Lesson 14
Agenda
● dictonaries
● Examples
● Challenge
● Assignment
Solution
defination
A dictionary is a collection which is unordered, changeable and indexed. In
Python dictionaries are written with curly brackets, and they have keys and
values.
example
Accessing item of a dictionary
Get the value of the "model" key:
x = thisdict["model"]
Access Items by using get()
method
Get the value of the "model" key:
x = [Link]("model")
Change values
Loop through a dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary,
but there are methods to return the values as well.
Print all key names in the dictionary, one by one:
Print all values in the dictionary, one by one:
You can also use the values() method to return values of a dictionary:
Loop through both keys and values, by using the items() method:
Check if key exists
To determine if a specified key is present in a dictionary use the in
keyword:
Check if "model" is present in the dictionary:
Dictionary length
Adding items
Removing items
❖ There are several methods to remove items from a dictionary:
❖ The pop() method removes the item with the specified key name:
pop() method
Deleting a single item
The popitem() method removes the last inserted item (in versions
before 3.7, a random item is removed instead):
example
Using del keyword
The clear() method empties the dictionary:
Copy a dictionary
❖ You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will
only be a reference to dict1, and changes made in dict1 will automatically also be
made in dict2.
❖ There are ways to make a copy, one way is to use the built-in Dictionary method
copy().
example
make a copy using dict().
Nested dictionaries
Another example
Challenge -1
Below are the two lists convert it into the dictionary
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
solution
challenge-2
Merge following two Python dictionaries into one
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
solution
Assignment
solution