COMMON OPERATIONS WITH DICTIONARIES

Credit: The information below has been obtained from http://introtopython.org and used with permission under the MIT license. 

There are a few common things you will want to do with dictionaries. These include adding new key-value pairs, modifying information in the dictionary, and removing items from dictionaries. Read the information below in order to find out more.

ADDING NEW KEY-VALUE PAIRS

To add a new key-value pair, you give the dictionary name followed by the new key in square brackets, and set that equal to the new value. We will show this by starting with an empty dictionary, and re-creating the dictionary from the example above.

[python]
# Create an empty dictionary.
python_words = {}

# Fill the dictionary, pair by pair.
python_words[‘list’] =’A collection of values that are not connected, but have an order.’
python_words[‘dictionary’] = ‘A collection of key-value pairs.’
python_words[‘function’] = ‘A named set of instructions that defines a set of actions in Python.’

# Print out the items in the dictionary.
# We will simplify this process later by using a loop
print("Word: List")
print("Meaning:", python_words[‘list’])
print("Word: Dictionary")
print("Meaning:", python_words[‘dictionary’])
print("Word: function")
print("Meaning:", python_words[‘function’])
[/python]

Try the code for yourself below.

MODIFYING VALUES IN A DICTIONARY

At some point you may want to modify one of the values in your dictionary. Modifying a value in a dictionary is pretty similar to modifying an element in a list. You give the name of the dictionary and then the key in square brackets, and set that equal to the new value.

[python]
python_words = {‘list’: ‘A collection of values that are not connected, but have an order.’,
‘dictionary’: ‘A collection of key-value pairs.’,
‘function’: ‘A named set of instructions that defines a set of actions in Python.’,
}

print(‘dictionary: ‘ + python_words[‘dictionary’])

# Clarify one of the meanings.
python_words[‘dictionary’] = ‘A collection of key-value pairs. Each key can be used to access its corresponding value.’

print(‘\ndictionary: ‘ + python_words[‘dictionary’])
[/python]

Try it for yourself by modifying the code below.

REMOVING KEY-VALUE PAIRS

You may want to remove some key-value pairs from one of your dictionaries at some point. You can do this using the

del

command, which is also used with lists. To remove a key-value pair, you give the

del

command, followed by the name of the dictionary, with the key that you want to delete. This removes the key and the value as a pair.

[python]
python_words = {‘list’: ‘A collection of values that are not connected, but have an order.’,
‘dictionary’: ‘A collection of key-value pairs.’,
‘function’: ‘A named set of instructions that defines a set of actions in Python.’,
}

# Show the current set of words and meanings.
# Print the entire dictionary in one statement
print("\n\nThese are the Python words I know:")
print(python_words)

# Remove the word ‘list’ and its meaning.
del python_words[‘list’]

# Show the current set of words and meanings.
print("\n\nThese are the Python words I know:")
print(python_words)
[/python]

We can also send the dictionary to a function. In this example, we will print the dictionary, delete a key-value pair, and then reprint the dictionary.

[python]
# define the function that will print the values of the dictionary
def show_words_meanings(print_python_words):
print(print_python_words)

# declare and define the dictionary
python_words = {‘list’: ‘A collection of values that are not connected, but have an order.’,
‘dictionary’: ‘A collection of key-value pairs.’,
‘function’: ‘A named set of instructions that defines a set of actions in Python.’,
}

# print the dictionary by sending it to the function
print("BEFORE DELETE")
show_words_meanings(python_words)

# Remove the word ‘list’ and its meaning.
del python_words[‘list’]

# print the dictionary again by sending it to the function
print("\nAFTER DELETE")
show_words_meanings(python_words)
[/python]

This will become much more effective when we learn how to use loops with dictionaries.

Try the code for yourself by retyping it or copying and pasting into the repl below.

MODIFYING KEYS IN A DICTIONARY

Modifying a value in a dictionary was straightforward, because nothing else depends on the value. Modifying a key is a little harder, because each key is used to unlock a value. We can change a key in two steps:

  • Make a new key, and copy the value to the new key.
  • Delete the old key, which also deletes the old value.

Here’s what this looks like. We will use a dictionary with just one key-value pair, to keep things simple.

[python]
# We have a spelling mistake!
python_words = {‘lisst’: ‘A collection of values that are not connected, but have an order.’}

# Create a new, correct key, and connect it to the old value.
# Then delete the old key.
python_words[‘list’] = python_words[‘lisst’]
del python_words[‘lisst’]

# Print the dictionary, to show that the key has changed.
print(python_words)
[/python]

Try the code for yourself by retyping it or copying and pasting into the repl below.

EXERCISES

Pet Names 2

  • Make a copy of your program from Pet Names.
    • Modify one of the values in your dictionary. You could clarify to name a breed, or you could change an animal from a cat to a dog.
    • Add a new key-value pair to your dictionary.
    • Remove one of the key-value pairs from your dictionary.
  • Bonus: Use a function to do all of the printing and altering in this problem.

Weight Lifting

  • Make a dictionary where the keys are the names of weight lifting exercises, and the values are the number of times you did that exercise.
    • Print out a series of statements such as “I did 10 bench presses”.
    • Modify one of the values in your dictionary, to represent doing more of that exercise.
    • Print out a series of statements such as “I did 10 bench presses” once again.
    • Add a new key-value pair to your dictionary.
    • Remove one of the key-value pairs from your dictionary.
    • Print out a series of statements such as “I did 10 bench presses”.
  • Bonus: Use a function to do all of the printing in this problem.