Accessing values in a dictionary is not done via the values()
method, but rather via bracket-notation (eg. my_dictionary[key]
). See d[key]
in the documentation.
Additionally, you could try just making a dict
instead of a full-blown function:
>>> card_points = {'A': 1, '2': 2, '3': 3, '4': 4, '5':5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
>>> card_points['A']
1
>>> card_points['5']
5
If you need it to be a function you can easily wrap this dictionary:
def get_card_value(s):
card_points = {'A': 1, '2': 2, '3': 3, '4': 4, '5':5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}
try:
return card_points[s]
except KeyError:
raise ValueError("No card found")
Note: KeyError
is the exception raised when trying to access a non-existent key in a dictionary, so if we encounter one of those, we can choose to instead raise our custom ValueError
exception.
Or if you want to get fancy (read: save some keystrokes):
>>> card_points = dict({str(i): i for i in range(2, 11)}, A=1, J=10, Q=10, K=10)
In the snippet above, {str(i): i for i in range(2, 11)}
uses a dictionary comprehension to create a dictionary mapping string values for the integers 2-10 to their numeric values. For the non-numeric cards, I pass them in as keyword arguments. Luckily, python's built-in dict
constructor can handle both of these at once!
So if you are just beginning you might want to use the first form rather than leverages a bunch of python's advanced features :)