Categories
Uncategorized

PYTHON DICTIONARIES FUN STUFF

First, let’s define what a dictionary is. In simple terms, a dictionary is a collection of key-value pairs, where each key is unique and is associated with a specific value. Dictionaries are denoted using curly braces ({}) and the key-value pairs are separated by commas. Here’s an example of a simple Python dictionary:

# Create a dictionary of sports teams
teams = {
  "basketball": "Boston Celtics",
  "football": "New England Patriots",
  "hockey": "Boston Bruins"
}

# Create a dictionary of breakfast foods
breakfast = {
  "cereal": "Lucky Charms",
  "eggs": "scrambled",
  "fruit": "strawberry"
}

# Create a mixed dictionary of sports teams and breakfast foods
mixed = {
  "basketball": "Boston Celtics",
  "cereal": "Lucky Charms",
  "eggs": "scrambled",
  "football": "New England Patriots",
  "fruit": "strawberry",
  "hockey": "Boston Bruins"
}

Now that you know what a Python dictionary is, let’s look at some of the common operations that you can perform on dictionaries.

One of the most basic operations is to access the value associated with a specific key in a dictionary. This is done using the square bracket notation, with the key inside the brackets. Here’s an example of accessing values in a dictionary:

# Access the value associated with the key "basketball"
teams["basketball"] # Output: "Boston Celtics"

# Access the value associated with the key "eggs"
breakfast["eggs"] # Output: "scrambled"

# Access the value associated with the key "fruit"
mixed["fruit"] # Output: "strawberry"

Another common operation is to add a new key-value pair to a dictionary. This is done using the square bracket notation, with the new key inside the brackets and the = operator to assign a value to the key. Here’s an example:

# Add a new key-value pair to the teams dictionary
teams["baseball"] = "Boston Red Sox"

# The dictionary now contains the key-value pair "baseball": "Boston Red Sox"

You can also update the value associated with an existing key using the same square bracket notation. Here’s an example:

# Update the value associated with the key "hockey"
teams["hockey"] = "Montreal Canadiens"

# The value associated with the key "hockey" has been updated to "Montreal Canadiens"

Now that you know how to create and manipulate dictionaries in Python. Hope this helps!