-
Integers, Floats and Strings 3
-
Lecture1.1
-
Lecture1.2
-
Lecture1.3
-
-
If Statements 3
-
Lecture2.1
-
Lecture2.2
-
Lecture2.3
-
-
Lists, Sets and Tuples 5
-
Lecture3.1
-
Lecture3.2
-
Lecture3.3
-
Lecture3.4
-
Lecture3.5
-
-
Loops 3
-
Lecture4.1
-
Lecture4.2
-
Lecture4.3
-
-
Functions 3
-
Lecture5.1
-
Lecture5.2
-
Lecture5.3
-
-
Dictionaries 3
-
Lecture6.1
-
Lecture6.2
-
Lecture6.3
-
-
Assertions 2
-
Lecture7.1
-
Lecture7.2
-
-
Classes 3
-
Lecture8.1
-
Lecture8.2
-
Lecture8.3
-
-
Matplotlib 2
-
Lecture9.1
-
Lecture9.2
-
Dictionary Functions 2
Example¶
An example bringing this all together is a function that checks if the key is in keys then prints the value, otherwise it checks if it is a value and in that case it just prints the value. If neither is true then it prints that is in neither.
In [16]:
#Example: Printing the value of a key, or if the value is not a key but in the dictionary the key
def dictPrint(dictionary, key):
if key in dictionary:
print(dictionary[key])
elif key in dictionary.values():
print(key)
else:
print("The key is not in the dictionary or in the values")
dictPrint(name,'First')
dictPrint(name,'Middle')
dictPrint(name,'John')
John
The key is not in the dictionary or in the values
John
For Loops and Dictionaries¶
When you call a loop on a dictionary it is going to iterate over the keys.
In [17]:
#If you iterate over a dictionary you iterate over the keys
for x in name:
print(x)
First
Last
Finally, tuples could be used for a key if you wanted. For example, here we are defining keys that are 2 element tuples for names. By then indexing with one of those tuples we get back the value.
In [18]:
#You could also have a key that is more complex like a tuple taking first and last name
grades = {}
grades[("John","Doe")] = "A"
grades[("Mary","Smith")] = "B+"
print(grades)
print(grades[("John","Doe")])
{('John', 'Doe'): 'A', ('Mary', 'Smith'): 'B+'}
A
This will not work if we feed just an element of the name. We have to use ("John", "Doe"), "John" will not work. The code below will fail.
In [19]:
#Notice we get an error if we use just the name John for the key
print(grades["John"])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-19-7be44dadf683> in <module>
1 #Notice we get an error if we use just the name John for the key
----> 2 print(grades["John"])
KeyError: 'John'
Prev
Dictionary Functions
Next
Introduction