Changes

Jump to: navigation, search

OPS435 Python Lab 4

69 bytes added, 14:18, 15 June 2017
PART 3 - Dictionaries
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''':<source>
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:<source>
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>
::#Loop Looping through the keys in a dictionary also provides a easy way to get the value for each key at the same time:<source>
for key in dict_york.keys():
print(key + '--->' + dict_york[key])
</source>
::#Even better than An alternative (possibly more efficient) method would be to cause both the above, both key and its value can to be extracted in into a single (using a for loop , and using a special object):<source>
for key, value in dict_york.items():
print(key + ' | ' + value)
13,420
edits

Navigation menu