Dungeon Coder

 

Keys of Value

Introducing Python Dictionaries

In addition to lists, python also allows us to make dictionaries. These are slightly more complex than lists. While lists consist of values stored at some index, dictionaries consist of items which themselves are key:value pairs. Take a look at the following code:

Above, you see a dictionary named spells. How do we know it's a dictionary? The name and = is followed by a {. Recall that lists can be identified by seeing a list name followed by an = followed by a [. While dictionaries can be written all on one line, it is customary to write them out over multiple lines indented appropriately as you see above. Within the { and } you see a few key:value pairs separated by commas. That is the syntax for python dictionaries, so you must follow those rules. Keys are always written first, followed by a colon : followed by the value associated with that key. The key is only followed by a comma if there is another key:value pair following. Otherwise, simply close out the dictionary definition with the }.

You can print dictionaries simply by including the dictionary name within a call to the built in print function. The output, however, is a bit messy looking.

You can access individual values within a dictionary by typing the dictionary name followed immediately (no spaces) by a [ and the key and a ]. Notice that in one of the print statements above.

I won't disect the for loop for you, but take a look at it and imagine how it works. Play around with some of the code and see if the output is impacted as you expect. You will become more familiar with dictionaries throughout further lessons.

Assignment:

    You may need to refer to earlier lessons.

  1. You can add a key:value pair to a dictionary simply by typing: dictionaryName[key] = value (be sure to substitute your actual dictionary's name, key, and value in place of this example). Add a few spells to the spell dictionary. Verify that the spells have been added by printing the dictionary.
  2. You can remove or delete an item (a key:value pair) from a dictionary by using the del keyword like this:
    del dictionaryName[key]
    . Remove one of the items from the dictionary.
  3. Try to print the value associated with a key that hasn't yet been added to the dictionary. Do this by typing something like:
    print(spells['LizardFrogLegSoup']
    What happens?
  4. Go to the official Python documentation web page on dictionaries.
  5. Read, test, and try to digest what you find at the link for question 4.

Join the Dungeon Crawl: A place for programmers to ponder, partake, and peruse postulations pertaining to programming, politics, potions, and pizza.

If you subscribe on Patreon, you will be granted access to the Dojo, a growing collection of quality computer science classes created and actively mantained and frequented by the Dungeon Master!

Become a Patron!

Glossary

Contact: dungeon_master@dungeoncoder.com