Basic Dictionaries
Dictionaries¶
A dictionary is a data structure that holds keys and associated values for them. The structure of defining a dictionary is:
dictionary = {key_1: value_1,
key_2: value_2,
....
key_n: value_n}
Each of the keys is going to be unique when we do this. Let’s do a first example where the two keys are first and last, and then the values are John and Doe.
#Define a dictionary
name = {"First":"John",
"Last":"Doe"}
We can get the values for a given key by indexing with the key. The format is:
dictionary[key]
Let's see the value for first and last.
#Find the value for First
print(name["First"])
#Find the value for Last
print(name["Last"])
We will get an error if we try to find the value for a key which does not actually exist in the dictionary.
#We will get a key error if we don't have the key in our dictionary
print(name["Middle"])
Adding a Key¶
You can add a key and value pair to a dictionary by doing the following:
dictionary[key] = value
Now, add in the key for "Middle" and define it as Edgar.
#You can assign a value to a key by indexing with brackets then passing the key a value
name["Middle"] = "Edgar"
#Print the value
print(name["Middle"])
If you print out a dictionary you get to see all the pairs of keys and values.
#Now our dictionary has three key value pairs
print(name)
You also can overwrite a value if you want. Let's change middle to be Michael.
#Change middle to Michael
name['Middle'] = "Michael"
print(name)
Getting Keys and Values¶
There are two dictionary functions that are very useful, keys() and values(). The first one returns all the keys in the dictionary and then values returns all the values in dictionary.
#Calling keys on the dictionary returns the keys
print(name.keys())
#Calling values on the dictionary returns the values of the dictionary
print(name.values())