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')
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)
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")])
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"])