chapter_six Flashcards
create a dictionary with the following variables
alien_0 = {‘color’: ‘green’, ‘points’: 5}
In Python, a dictionary is wrapped in braces, {}, with a series of key-value pairs inside the braces.
Every key is connected to its value by a colon, and individual key-value pairs are separated by commas.
You can store as many key-value pairs as you want in a dictionary.
A dicitonary in Python is a collection of key-value pairs. Each key is connected to a value, and you can use a key to access the vluae associated with that key. A key’s value can be a number, a string, a list, or even another dictionary.#
A key-value pair is a set of values associated with each other. When you provide a key, Python returns the value associated with that key.
Get a value associated with a key out of a dictionary
To get the value associated with a key, give the name of the dictionary and then place the key inside a set of brackets.
Add key-value pairs to an allready existing dictionary below.
Dictionaries are dynamic structures, and you can add newe key-value pairs to a dictionary at any time.
For example. to add a new key-value pair, you would give the name of the dicitionary followed by the new key in square brackets along with the new value.
Change the value of a key in a dictionary.
To modify a value in a dictionary, give the name of the dictionary with the key in the square brackets and then the new value you want associated with that key.
Remove one of the Key-value pairs below.
When you no longer need a piece of information that’s stored in a dictonary, you can use the del statement to completely remove the key-value pair. All del needs is the name of the dictionary and the key that you want to remove.
Be aware that the key-value pair is removed permanently.
Get a value that doesn’t exist in the dictionary below, but in a way that avoids errors.
Using keys in square brackets to retrive the value you’re interested in from a dictionary might cause one potential problem:
if the key you ask for doesn’t exist, you’ll get an error.
For dictionaries, specifically, you can use the ‘get( )’ method to set a default value that will be returned it the requested key doesn’t exist.
The ‘get( )’ method requires a key as a first argument. As a second optional argument, you can pass the value to be returned if the key doesn’t exist.
If there’s a chance the key you’re asking for might not exist, consider using the ‘get( )’ method instead of the square bracket notation.