Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 4

290 bytes added, 11:37, 18 August 2017
PART 3 - Dictionaries
ipython3
</source>
::#Let's begin by creating a new dictionary (for practice):<sourcelang="python">
dict_york = {'Address': '70 The Pond Rd', 'City': 'Toronto', 'Postal Code': 'M3J3M6'}
</source>You should note that the syntax to define a dictionary is similar to defining sets (i.e. using '''{}''').<br>Unlike sets, dictionaries use '''<code>key:value</code>''' pairs within the dictionary, each ''key:value'' pair in turn, are separated by commas.<br><br>You can get help associated with your dictionary by using functions such as '''dir()''' and '''help()'''.<br><br>
::#Issue the following and note all the available functions available and how to obtain assistance with dictionary objects:<sourcelang="python">
dir(dict_york)
help(dict_york)
</source>All values can be viewed by using the '''dictionary.values()''' function. This particular function provides a '''list''' containing all values.<br><br>
::#To demonstrate, issue the following:<sourcelang="python">
help(dict_york.values)
dict_york.values()
</source>All keys to access the ''key:pair'' values within a dictionary can be viewed by using the '''dictionary.keys()''' function. This function provides a '''list''' containing all keys<br><br>
::#To demonstrate this, issue the following:<sourcelang="python">
help(dict_york.keys)
dict_york.keys()
</source>Armed with this information, We can retrieve <u>individual</u> values from a dictionary by provide the key associated with the key:pair value<br><br>
::#For example, issue the following:<sourcelang="python">
dict_york['Address']
dict_york['Postal Code']
</source>
::#Dictionary keys can be any '''immutable''' values (i.e. not permitted for value to be changed). Types of values include: '''strings''', '''numbers''', and '''tuples'''. Trying adding a couple new keys and values to the dictionary by issuing:<sourcelang="python">
dict_york['Country'] = 'Canada'
dict_york
dict_york.keys()
</source>
::#Let's add another key:value pair to our dictionary to change the province key:pair value to BC:<sourcesourc lang="python"e>
dict_york['Province'] = 'BC'
dict_york
dict_york.keys()
</source>'''WARNING: Dictionary keys must be unique'''. Attempting to add a key that already exists in the dictionary will <u>overwrite</u> the existing value for that key!<br><br>
::#To demonstrate, issue the following:<sourcelang="python">
dict_york['Province'] = 'ON'
dict_york
dict_york.keys()
</source>You should notice that key value for 'Province' has been changed back to 'ON'.<br><br>These lists that contain the values and keys of the dictionary are not <u>real</u> python lists - they are "views of the dictionary" and therefore are <u>immutable</u>. You could change these views into usable lists by using the '''list()''' function (where the index can be used to access individual values).<br><br>
::#For example, issue the following:<sourcelang="python">
list_of_keys = list(dict_york.keys())
list_of_keys[0]
</source>
::#In addition, lists can be changed into sets if we would like to perform comparisons with another set. To demonstrate, issue the following:<sourcelang="python">
set_of_keys = set(dict_york.keys())
set_of_values = set(dict_york.values())
set_of_keys | set_of_values
</source>
::#Lists can be used with '''for loops'''. To Demonstrate, issue the following:<sourcelang="python">
list_of_keys = list(dict_york.keys())
for key in list_of_keys:
</source>Additional Information regarding Dictionaries:<ul><li>The values and keys can be looped over using the index as well
::#The '''range()''' function provides a list of numbers in a range.</li><li>The '''len()''' function provides a the number of items in a list.</li><li>Used together '''len()''' and '''range()''' can be used to create a list of usable indexes for a specific list</li></ul><br>Let's create a dictionary by using lists in order to store our dictionary data. First, we need to pair the keys and values of two separate lists.<br><br>
::#Issue the following:<sourcelang="python">
list_of_keys = list(dict_york.keys())
list_of_values = list(dict_york.values())
list_of_values[0]
</source>Now, let's use these '''newly-created lists''', '''len()''' &amp; '''range()''' functions with a '''for loop''' to construct our dictionary:<br><br>
::#Issue the following:<sourcelang="python">
list_of_keys = list(dict_york.keys())
list_of_values = list(dict_york.values())
print(list_of_keys[index] + '--->' + list_of_values[index])
</source>
::#Looping using indexes is not the best way to loop through a dictionary. A new dictionary could be created using this method, but this is '''not good''':<sourcelang="python">
list_of_keys = list(dict_york.keys())
list_of_values = list(dict_york.values())
new_dictionary[list_of_keys[index]] = list_of_values[index]
</source>
::#The above method uses a lot of memory and loops. The best method to create a dictionary from two lists is to use the zip() function:<sourcelang="python">
list_of_keys = list(dict_york.keys())
list_of_values = list(dict_york.values())
new_dictionary = dict(zip(list_of_keys, list_of_values))
</source>
::#Looping through the keys in a dictionary also provides a easy way to get the value for each key at the same time:<sourcelang="python">
for key in dict_york.keys():
print(key + '--->' + dict_york[key])
</source>
::#An alternative (possibly more efficient) method would be to cause both the key and its value to be extracted into a single (using a for loop, and using a special object):<sourcelang="python">
for key, value in dict_york.items():
print(key + ' | ' + value)
:'''Perform the Following Instructions'''
::#Create the '''~/ops435/lab4/lab4c.py''' script. The purpose of this script will be to create dictionaries, extract data from dictionaries, and to make comparisons between dictionaries.
::#Use the following as a template:<sourcelang="python">
#!/usr/bin/env python3
cd ~/ops435/lab4/
pwd #confirm that you are in the right directory
ls CheckLab4.py || wget matrix.senecachttps://raw.ongithubusercontent.cacom/~acoatleySeneca-willisCDOT/ops435/master/LabCheckScripts/CheckLab4.py
python3 ./CheckLab4.py -f -v lab4c
</source>