5) Lists & Dictionaries

Lists and Dictionaries are the best places to store a lot of local information.

Lists store information as either strings, numbers, or Boolean values. Like phrases, the first item in their index is read as the 0th variable.

Lists always stay in the same order. This means that information can be added in a specific order. Below is an example of a list.

Helpful Commands

Some quick commands are listed below (list is used a variable, the list’s variable name should go in that position):

list.append(x): adds information to the end of the list
list.insert(z, x): inserts information into a list. z represents where in the list, x represents what is being added
list.sort(): sorts the list in alphabetical order
list.remove(x): removes x from the list
del list[x]: removes the item that is located at the x position in the list
list.copy(): copies the list
list.reverse(): reverses the list
list.pop(x): removes the x value from the list. This can be then stored as a variable
len(list): finds the total amount of items in the list

Tuples are like lists except that they cannot be changed or altered. They are represented with a pair of parentheses instead of brackets.
tuple = (3, 20)

Dictionaries are essentially lists except that each key contains a corresponding value. This means that the order of a dictionary does not matter.

Helpful Commands

Unlike lists, dictionary items are not in a specific order. Keys are used to define their corresponding value. Because of this, changing dictionaries differs greatly from lists. Below are some commands that can be used to change or alter dictionaries.

dictionary.get(x, y): This finds the key, x, and delivers the value that corresponds with it. y does not need to be included, but it acts as a failsafe if x is not in the dictionary. If x is not in the dictionary, y will be the output.
dictionary[x]= y: A quick way to insert keys and values into a dictionary, the x is the key and y is the value
dictionary.update({x: y, a:b}): Another way to add values to a dictionary. This is helpful for adding multiple keys and values (you can write more keys and values in the brackets with a comma separating each set)
dictionary.items(): delivers a line of code with every key and phrase. This will be useful in future lessons.

Leave a Reply